Python django.forms.Select() Examples

The following are 30 code examples of django.forms.Select(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms , or try the search function .
Example #1
Source File: forms.py    From registrasion with Apache License 2.0 11 votes vote down vote up
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm 
Example #2
Source File: forms.py    From horas with MIT License 8 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.protege = kwargs.pop("protege")

        super().__init__(*args, **kwargs)

        meeting = kwargs.get("instance")
        choices = [("", _("--- Selecciona ---"))]
        choices.extend(meeting.mentor.get_meeting_formats())
        self.fields["format"].widget = Select(choices=choices)
        self.fields["format"].required = True
        self.fields["format"].label = _("Formato")

        self.fields["message"].required = True
        self.fields["message"].label = _("Mensaje")
        self.fields["message"].help_text = _(
            "En este mensaje, explica de que quieres hablar en la reunión, por qué escogiste a esta persona. Trata de dejarle saber al mentor los temas que quieres hablar durante la reunión. Piensa que el mentor se tiene que preparar y tu debes estar preparado antes de la reunión. Este mensaje debe ayudar a ambos a saber que esperar de la reunión."
        ) 
Example #3
Source File: forms.py    From freedomvote with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(PoliticianForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select) or isinstance(field.widget, forms.EmailInput):
                field.widget.attrs.update({
                    'class': 'form-control'
                })
            if field_name == 'party':
                field.choices = [('', '---------')]
                field.choices += [
                    (p.id, p.name)
                    for p
                    in Party.objects.order_by('name')
                ]

            if isinstance(field.widget, forms.Textarea):
                field.widget.attrs.update({
                    'class': 'form-control',
                    'rows': 2,
                }) 
Example #4
Source File: forms.py    From registrasion with Apache License 2.0 7 votes vote down vote up
def set_fields(cls, category, products):
        choices = []

        if not category.required:
            choices.append((0, "---"))

        for product in products:
            choice_text = "%s -- $%d each" % (product.name, product.price)
            choices.append((product.id, choice_text))

        cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.Select,
            choices=choices,
            initial=0,
            empty_value=0,
            coerce=int,
        )

        cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField(
            label="Quantity",  # TODO: internationalise
            min_value=0,
            max_value=500,  # Issue #19. We should figure out real limit.
        ) 
Example #5
Source File: forms.py    From GetTogether with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def __init__(self, attrs=None):
        self.time_class = "timepicker"
        if not attrs:
            attrs = {}
        if "time_class" in attrs:
            self.time_class = attrs.pop("time_class")
        if "class" not in attrs:
            attrs["class"] = "time"

        widgets = (
            forms.Select(
                attrs=attrs, choices=[(i + 1, "%02d" % (i + 1)) for i in range(0, 12)]
            ),
            forms.Select(
                attrs=attrs, choices=[(i, "%02d" % i) for i in range(00, 60, 15)]
            ),
            forms.Select(attrs=attrs, choices=[("AM", _("AM")), ("PM", _("PM"))]),
        )

        super(TimeWidget, self).__init__(widgets, attrs) 
Example #6
Source File: forms.py    From yournextrepresentative with GNU Affero General Public License v3.0 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        from .election_specific import shorten_post_label
        election = kwargs.pop('election')
        super(AddCandidacyPickPostForm, self).__init__(*args, **kwargs)
        self.fields['post'] = forms.ChoiceField(
            label=_('Post in %s') % election.name,
            choices=[('', '')] + sorted(
                [
                    (post.extra.slug,
                     shorten_post_label(post.label))
                    for post in Post.objects.select_related('extra').filter(extra__elections=election)
                ],
                key=lambda t: t[1]
            ),
            widget=forms.Select(attrs={'class': 'post-select'}),
        ) 
Example #7
Source File: widgets.py    From Dailyfresh-B2C with Apache License 2.0 7 votes vote down vote up
def render(self, name, value, attrs=None):
        if not self._isiterable(value):
            value = [value]

        if len(value) <= 1:
            # delegate to main widget (Select, etc...) if not multiple values
            value = value[0] if value else ''
            return super(BaseCSVWidget, self).render(name, value, attrs)

        # if we have multiple values, we need to force render as a text input
        # (otherwise, the additional values are lost)
        surrogate = forms.TextInput()
        value = [force_text(format_value(surrogate, v)) for v in value]
        value = ','.join(list(value))

        return surrogate.render(name, value, attrs) 
Example #8
Source File: forms.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def prepare_select(self, field):
        field_attrs = field.build_field_attrs()
        widget_attrs = field.build_widget_attrs()

        field_attrs.update({
            'widget': forms.Select(attrs=widget_attrs)
        })

        if field.choice_values:
            choice_list = field.get_choices()
            if not field.required:
                choice_list.insert(0, ('', field.placeholder_text or _('Please select an option')))
            field_attrs.update({
                'choices': choice_list
            })
        return forms.ChoiceField(**field_attrs) 
Example #9
Source File: markup.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        widgets = (
            forms.Textarea(attrs={'cols': 70, 'rows': 20}),
            forms.Select(),
            forms.CheckboxInput(),
        )
        super(MarkupContentWidget, self).__init__(widgets) 
Example #10
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(KoScheduleForm, self).__init__(*args, **kwargs)
        # if hasattr(self.request, "project") and self.request.project is not None:
        #     xform = XForm.objects.filter(
        #         Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True) |
        #         Q(fieldsightformlibrary__project=self.request.project) |
        #         Q(fieldsightformlibrary__organization=self.request.organization))

        if hasattr(self.request, "organization") and self.request.organization is not None:
            xform = XForm.objects.filter(
                Q(user=self.request.user) |
                Q(user__user_profile__organization=self.request.organization), deleted_xform=None)
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True), deleted_xform=None)
        self.fields['form'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['form'].empty_label = None
        self.fields['form'].label = "Select Form" 
Example #11
Source File: notes.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(NoteForm, self).__init__(*args, **kwargs)
        note = kwargs['instance']
        self.fields['sender'] = forms.ChoiceField(
            label=_('From'),
            choices=note.get_sender_choices(),
            widget=forms.Select(attrs={'class': 'span12'})
        )

        self.fields['body'].widget = AutocompleteTextarea(
            rows=20,
            choices=Template.templates()
        )

        if note.order:
            url = reverse('notes-render_template', args=[note.order.pk])
            self.fields['body'].widget.attrs['data-url'] = url 
Example #12
Source File: forms.py    From dissemin with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        We change the widget of the fields
        We get the original form, register all repositories, create the list of protocols.
        If a repo exists, we check that its protocol will be in the list. Otherwise the protocol of a repo with a currently not registered protocol would be overwritten.
        """
        super().__init__(*args, **kwargs)

        # Protocol
        # Get the list with names of protocols
        protocol_registry.load()
        choices = [(key, str(value)) for key, value in protocol_registry.dct.items()]
        # If the repo uses a protocol not in the list, we add this value, otherwise it is overriden on saving
        if self.instance.protocol:
            if self.instance.protocol not in protocol_registry.dct.keys():
                choices += [(self.instance.protocol,self.instance.protocol)]
        # Sort and populate the form
        choices = sorted(choices, key=lambda protocol: protocol[1].lower(),)
        self.fields['protocol'].widget = forms.Select(choices=choices) 
Example #13
Source File: forms.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        widgets = [forms.Select(), forms.TextInput(attrs={'size': 8, 'maxlength': 8})]
        kwargs['widgets'] = widgets
        super(SupervisorWidget, self).__init__(*args, **kwargs) 
Example #14
Source File: djangocms_forms_tags.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_select(field):
    return isinstance(field.field.widget, forms.Select) 
Example #15
Source File: table_views.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_method_filter_widget(self, filter_obj, full_field_name, method):
        if filter_obj.choices:
            return forms.Select(choices=FilterChoiceIterator(filter_obj.choices))
        else:
            return forms.TextInput() 
Example #16
Source File: forms.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(AddTicketForm, self).__init__(*args, **kwargs)
        self.fields['vm'].choices = [('', _('Select Server'))] + \
            list(get_vms(request, prefetch_tags=False).values_list('hostname', 'alias')) 
Example #17
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_constructor_generator(self):
        """
        If choices is passed to the constructor and is a generator, it can be
        iterated over multiple times without getting consumed.
        """
        def get_choices():
            for i in range(5):
                yield (i, i)

        widget = Select(choices=get_choices())
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2" selected>2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            </select>"""
        ))
        self.check_html(widget, 'num', 3, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3" selected>3</option>
            <option value="4">4</option>
            </select>"""
        )) 
Example #18
Source File: test_textfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_generates_select_widget(self):
        """A TextField with choices uses a Select widget."""
        f = models.TextField(choices=[('A', 'A'), ('B', 'B')])
        self.assertIsInstance(f.formfield().widget, forms.Select) 
Example #19
Source File: admin.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(DomainAdminForm, self).__init__(*args, **kwargs)
        self.fields['master'].required = False
        self.fields['user'].required = False
        self.fields['user'].widget = forms.Select(
            choices=BLANK_CHOICE_DASH + [(i.id, i.username) for i in User.objects.all()]
        ) 
Example #20
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_constuctor(self):
        widget = Select(choices=[(1, 1), (2, 2), (3, 3)])
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="1">1</option>
            <option value="2" selected>2</option>
            <option value="3">3</option>
            </select>"""
        )) 
Example #21
Source File: table_views.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_field_filter_widget(self, filter_obj, full_field_name, field):
        if filter_obj.choices:
            return forms.Select(choices=FilterChoiceIterator(filter_obj.choices))
        else:
            formfield = field.formfield() if hasattr(field, 'formfield') else None
            if formfield:
                widget = formfield.widget
                if hasattr(widget, 'choices'):
                    widget.choices = FilterChoiceIterator(widget.choices, field)

                if not isinstance(widget, forms.widgets.Textarea):
                    return widget

            return forms.TextInput() 
Example #22
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ForeignKey(self):
        self.assertFormfield(Event, 'main_band', forms.Select) 
Example #23
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deepcopy(self):
        """
        __deepcopy__() should copy all attributes properly (#25085).
        """
        widget = Select()
        obj = copy.deepcopy(widget)
        self.assertIsNot(widget, obj)
        self.assertEqual(widget.choices, obj.choices)
        self.assertIsNot(widget.choices, obj.choices)
        self.assertEqual(widget.attrs, obj.attrs)
        self.assertIsNot(widget.attrs, obj.attrs) 
Example #24
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_constructor_generator(self):
        """
        If choices is passed to the constructor and is a generator, it can be
        iterated over multiple times without getting consumed.
        """
        def get_choices():
            for i in range(5):
                yield (i, i)

        widget = Select(choices=get_choices())
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2" selected>2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            </select>"""
        ))
        self.check_html(widget, 'num', 3, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3" selected>3</option>
            <option value="4">4</option>
            </select>"""
        )) 
Example #25
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_constuctor(self):
        widget = Select(choices=[(1, 1), (2, 2), (3, 3)])
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="1">1</option>
            <option value="2" selected>2</option>
            <option value="3">3</option>
            </select>"""
        )) 
Example #26
Source File: test_select.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_constructor_attrs(self):
        """
        Select options shouldn't inherit the parent widget attrs.
        """
        widget = Select(
            attrs={'class': 'super', 'id': 'super'},
            choices=[(1, 1), (2, 2), (3, 3)],
        )
        self.check_html(widget, 'num', 2, html=(
            """<select name="num" class="super" id="super">
              <option value="1">1</option>
              <option value="2" selected>2</option>
              <option value="3">3</option>
            </select>"""
        )) 
Example #27
Source File: test_base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_deepcopies_widget_instance(self):
        class CustomChoiceField(ChoiceField):
            widget = Select(attrs={'class': 'my-custom-class'})

        class TestForm(Form):
            field1 = CustomChoiceField(choices=[])
            field2 = CustomChoiceField(choices=[])

        f = TestForm()
        f.fields['field1'].choices = [('1', '1')]
        f.fields['field2'].choices = [('2', '2')]
        self.assertEqual(f.fields['field1'].widget.choices, [('1', '1')])
        self.assertEqual(f.fields['field2'].widget.choices, [('2', '2')]) 
Example #28
Source File: forms.py    From freedomvote with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(PartyPoliticianForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select):
                field.widget.attrs.update({
                    'class': 'form-control'
                }) 
Example #29
Source File: forms.py    From pets with MIT License 5 votes vote down vote up
def _build_choice_field(label, choices=None, required=False):
    empty_choice = (("", "------------"),)
    field = forms.ChoiceField(
        widget=forms.Select(attrs={"class": "form-control"}),
        label=label,
        choices=empty_choice,
        required=required,
    )
    if choices:
        field.choices += choices
    return field 
Example #30
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_with_choices(self):
        self.assertFormfield(Member, 'gender', forms.Select)