Python django.forms.Select() Examples

The following are 30 code examples for showing how to use django.forms.Select(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: notes.py    License: 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 2
Project: kobo-predict   Author: awemulya   File: forms.py    License: 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 3
Project: dissemin   Author: dissemin   File: forms.py    License: 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 4
Project: yournextrepresentative   Author: mysociety   File: forms.py    License: GNU Affero General Public License v3.0 6 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 5
Project: GetTogether   Author: GetTogetherComm   File: forms.py    License: BSD 2-Clause "Simplified" License 6 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
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 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 7
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 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 8
Project: Dailyfresh-B2C   Author: BeanWei   File: widgets.py    License: Apache License 2.0 6 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 9
Project: freedomvote   Author: freedomvote   File: forms.py    License: GNU General Public License v3.0 6 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 10
Project: djangocms-forms   Author: mishbahr   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 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 11
Project: horas   Author: SoPR   File: forms.py    License: MIT License 6 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 12
Project: coursys   Author: sfu-fas   File: markup.py    License: GNU General Public License v3.0 5 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 13
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 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
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        widgets = [forms.Select() for c in CATEGORY_CHOICES]
        kwargs['widgets'] = widgets
        super(AccountsWidget, self).__init__(*args, **kwargs) 
Example 15
Project: fermentrack   Author: thorrak   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(GravityLogCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['class'] = "form-control"
        self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(),
                                                  widget=forms.Select(attrs={'class': 'form-control',
                                                                             'data-toggle': 'select'})) 
Example 16
Project: fermentrack   Author: thorrak   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SensorAttachForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['class'] = "form-control"
        self.fields['sensor'] = forms.ChoiceField(required=True, choices=self.get_sensor_choices(),
                                                  widget=forms.Select(attrs={'class': 'form-control',
                                                                             'data-toggle': 'select'}))
        self.fields['temp_controller'] = forms.ChoiceField(required=True, choices=self.get_controller_choices(),
                                                           widget=forms.Select(attrs={'class': 'form-control',
                                                                                      'data-toggle': 'select'})) 
Example 17
Project: fermentrack   Author: thorrak   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TiltCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['class'] = "form-control"
        self.fields['tiltbridge'] = forms.ChoiceField(required=False, choices=self.get_tiltbridge_choices(),
                                                      widget=forms.Select(attrs={'class': 'form-control',
                                                                                 'data-toggle': 'select'})) 
Example 18
Project: fermentrack   Author: thorrak   File: device_forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TempControlForm, self).__init__(*args, **kwargs)
        # for this_field in self.fields:
        #     self.fields[this_field].widget.attrs['class'] = "form-control"
        self.fields['profile'] = forms.ChoiceField(required=False,
                                                   choices=self.get_profile_choices(),
                                                   widget=forms.Select(attrs={'class': 'form-control'}))

    # Check that the Start At format is valid, and if it is, replace it with a datetime delta object 
Example 19
Project: fermentrack   Author: thorrak   File: beer_forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(BeerCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['class'] = "form-control"
        self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(),
                                                  widget=forms.Select(attrs={'class': 'form-control',
                                                                             'data-toggle': 'select'})) 
Example 20
Project: django-import-export-celery   Author: auto-mat   File: admin.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["resource"].widget = forms.Select(
            choices=self.instance.get_resource_choices()
        ) 
Example 21
Project: dissemin   Author: dissemin   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Letter of Declaration
        Get the list of user friendly names of the generating functions. We need them as tuple for djangos choices
        """
        super().__init__(*args, **kwargs)

        choices = sorted([(value, value) for value in REGISTERED_DECLARATION_FUNCTIONS], key=lambda item: item[1])
        self.fields['function_key'].widget = forms.Select(choices=choices) 
Example 22
Project: volontulo   Author: CodeForPoznan   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Administrator contant form initialization.

        Administrator choice need to be here, as new Django release tries to
        import this form during migrations, even if user table is not
        available.
        """
        super(AdministratorContactForm, self).__init__(*args, **kwargs)
        self.administrator = forms.Select(
            choices=get_administrators_emails().items(),
        ) 
Example 23
Project: django-rdf-io   Author: rob-metalinkage   File: admin.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def render(self, name, value, attrs=None):
        self.choices = self.form_instance.fields['next_service'].choices
        s = super(forms.Select, self).render(name, value, attrs)
        h="<BR/>"
        ind= "-> {}<BR/>"
        
        for next in  self.form_instance.instance.next_chain():
            h = h+ ind.format( str(next))
            ind = "--" + ind
  
        
        return mark_safe(s+ h ) 
Example 24
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        subject = kwargs.pop('subject', None)
        contacts = kwargs.pop('contacts', None)
        super(ContactForm, self).__init__(*args, **kwargs)

        if subject:
            self.fields['subject'].initial = subject

        if contacts:
            contact_choices = []
            for contact in contacts:
                contact_choices.append([contact.email, '{name}, {role}'.format(name=contact.name, role=contact.role)])
            self.fields['recipient'].widget = forms.Select(choices=contact_choices) 
Example 25
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        settings = kwargs.pop('settings', None)
        super(GeneratedPluginSettingForm, self).__init__(*args, **kwargs)

        for field in settings:

            object = field['object']
            if field['types'] == 'char':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False)
            elif field['types'] == 'rich-text' or field['types'] == 'text' or field['types'] == 'Text':
                self.fields[field['name']] = forms.CharField(widget=forms.Textarea, required=False)
            elif field['types'] == 'json':
                self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                                       choices=field['choices'],
                                                                       required=False)
            elif field['types'] == 'number':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'}))
            elif field['types'] == 'select':
                self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices']))
            elif field['types'] == 'date':
                self.fields[field['name']] = forms.CharField(
                    widget=forms.DateInput(attrs={'class': 'datepicker'}))
            elif field['types'] == 'boolean':
                self.fields[field['name']] = forms.BooleanField(
                    widget=forms.CheckboxInput(attrs={'is_checkbox': True}),
                    required=False)

            self.fields[field['name']].initial = object.processed_value
            self.fields[field['name']].help_text = object.setting.description 
Example 26
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        settings = kwargs.pop('settings', None)
        super(GeneratedSettingForm, self).__init__(*args, **kwargs)

        for field in settings:

            object = field['object']
            if object.setting.types == 'char':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False)
            elif object.setting.types == 'rich-text' or object.setting.types == 'text':
                self.fields[field['name']] = forms.CharField(widget=forms.Textarea, required=False)
            elif object.setting.types == 'json':
                self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                                       choices=field['choices'],
                                                                       required=False)
            elif object.setting.types == 'number':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'}))
            elif object.setting.types == 'select':
                self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices']))
            elif object.setting.types == 'date':
                self.fields[field['name']] = forms.CharField(
                    widget=forms.DateInput(attrs={'class': 'datepicker'}))
            elif object.setting.types == 'boolean':
                self.fields[field['name']] = forms.BooleanField(
                    widget=forms.CheckboxInput(attrs={'is_checkbox': True}),
                    required=False)

            self.fields[field['name']].label = object.setting.pretty_name
            self.fields[field['name']].initial = object.processed_value
            self.fields[field['name']].help_text = object.setting.description 
Example 27
Project: urbanfootprint   Author: CalthorpeAnalytics   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):

        if 'config_entity_choices' in kwargs:
            config_entity_choices = kwargs.pop('config_entity_choices')
        else:
            config_entity_choices = []

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

        self.fields['config_entity'] = forms.ChoiceField(
            choices=config_entity_choices,
            widget=forms.Select(attrs={'class': 'form-control config-entity-select'})
        ) 
Example 28
Project: urbanfootprint   Author: CalthorpeAnalytics   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        initial_role = None
        role_choices = []

        if 'initial_role' in kwargs:
            initial_role = kwargs.pop('initial_role')
        if 'role_choices' in kwargs:
            role_choices = kwargs.pop('role_choices')

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

        self.fields['role'] = forms.ChoiceField(choices=role_choices, widget=forms.Select(attrs={'class': 'form-control'}))

        if initial_role:
            self.fields['role'].initial = initial_role 
Example 29
Project: yournextrepresentative   Author: mysociety   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        election = kwargs.pop('election')
        post = kwargs.pop('post')
        super(AddCandidacyPickPartyForm, self).__init__(*args, **kwargs)
        party_set = PartySet.objects.get(postextra__slug=post)

        self.fields['party'] = \
            forms.ChoiceField(
                label=_("Party in {election}").format(
                    election=election.name,
                ),
                choices=party_set.party_choices(),
                required=False,
                widget=forms.Select(
                    attrs={
                        'class': 'party-select party-select-' + election.slug
                    }
                ),
            )
        if election.party_lists_in_use:
            # Then add a field to enter the position on the party list
            # as an integer:
            self.fields['party_list_position'] = forms.IntegerField(
                label=_("Position in party list ('1' for first, '2' for second, etc.)"),
                min_value=1,
                required=False,
                widget=forms.NumberInput(
                    attrs={
                        'class': 'party-position party-position-' + election.slug
                    }
                )
            ) 
Example 30
Project: GetTogether   Author: GetTogetherComm   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["view"].widget = forms.Select(choices=url_choices())