django.forms.Select - python examples

Here are the examples of the python api django.forms.Select taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

41 Examples 7

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    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)

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
    def __init__(self, *args, request=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['space'].label_from_instance = lambda obj: obj.satle
        self.fields['space'].queryset = Space.qs_for_request(request).order_by('slug')
        choices = [('0', _('no'))] * 6 + [('1', _('yes'))] + [('0', _('no'))] * 3
        self.fields['can_edit'].widget = Select(choices=choices)

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
    def __init__(self, *args, **kwargs):

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

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

        self.fields['config_ensaty'] = forms.ChoiceField(
            choices=config_ensaty_choices,
            widget=forms.Select(attrs={'clast': 'form-control config-ensaty-select'})
        )

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
    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={'clast': 'form-control'}))

        if initial_role:
            self.fields['role'].initial = initial_role

3 View Complete Implementation : forms.py
Copyright MIT License
Author : CodeForPoznan
    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(),
        )

3 View Complete Implementation : admin.py
Copyright Apache License 2.0
Author : erigones
    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()]
        )

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        author = self.fields['author']
        author.widget = RelatedFieldPopupFormWidget(
            widget=Select2Widget(choices=author.choices) if _select2 else \
                    forms.Select(choices=author.choices),
            new_url=reverse_lazy("library:new-author"))

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def __init__(self, *args, **kwargs):
        super(AuthorRatingForm, self).__init__(*args, **kwargs)
        author = self.fields['author']
        author.widget = RelatedFieldPopupFormWidget(
            widget=forms.Select(choices=author.choices),
            new_url=reverse_lazy("library:new-author"))

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def __init__(self, *args, **kwargs):
        super(MultipleRelatedObjectForm, self).__init__(*args, **kwargs)
        author = self.fields['author']
        author.widget = RelatedFieldPopupFormWidget(
            widget=Select2Widget(choices=author.choices) if _select2 else \
                    forms.Select(choices=author.choices),
            new_url=reverse_lazy("library:new-author"))
        book = self.fields['book']
        book.widget = RelatedFieldPopupFormWidget(
            widget=forms.Select(choices=book.choices),
            new_url=reverse_lazy("library:books:create"))

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        author = self.fields['author']
        author.widget = RelatedFieldPopupFormWidget(
            widget=Select2Widget(choices=author.choices) if _select2 else \
                    forms.Select(choices=author.choices),
            new_url=reverse_lazy("new-author"))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : ic-labs
    def __init__(self, *args, **kwargs):
        """
        Set the default widgets and queryset.
        """
        widgets = kwargs.pop('widgets', (
            forms.Select,
            AdminTextareaWidget,
            AdminTextareaWidget,
        ))
        super(RecurrenceRuleWidget, self).__init__(
            widgets=widgets, *args, **kwargs)
        self.queryset = models.RecurrenceRule.objects.all()

3 View Complete Implementation : poi_form.py
Copyright Apache License 2.0
Author : Integreat
    def __init__(self, *args, **kwargs):

        logger.info(
            'New POITranslationForm with args %s and kwargs %s',
            args,
            kwargs
        )

        # pop kwarg to make sure the super clast does not get this param
        self.region = kwargs.pop('region', None)
        self.language = kwargs.pop('language', None)

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

        self.fields['public'].widget = forms.Select(choices=self.PUBLIC_CHOICES)

3 View Complete Implementation : test_base.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_field_deepcopies_widget_instance(self):
        clast CustomChoiceField(ChoiceField):
            widget = Select(attrs={'clast': 'my-custom-clast'})

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

        f = TestForm()
        f.fields['field1'].choices = [('1', '1')]
        f.fields['field2'].choices = [('2', '2')]
        self.astertEqual(f.fields['field1'].widget.choices, [('1', '1')])
        self.astertEqual(f.fields['field2'].widget.choices, [('2', '2')])

3 View Complete Implementation : test_i18n.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_select_translated_text(self):
        # Deep copying translated text shouldn't raise an error.
        clast CopyForm(Form):
            degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))

        CopyForm()

3 View Complete Implementation : test_select.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_constructor_attrs(self):
        """
        Select options shouldn't inherit the parent widget attrs.
        """
        widget = Select(
            attrs={'clast': 'super', 'id': 'super'},
            choices=[(1, 1), (2, 2), (3, 3)],
        )
        self.check_html(widget, 'num', 2, html=(
            """<select name="num" clast="super" id="super">
              <option value="1">1</option>
              <option value="2" selected>2</option>
              <option value="3">3</option>
            </select>"""
        ))

3 View Complete Implementation : test_select.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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>"""
        ))

3 View Complete Implementation : test_select.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_deepcopy(self):
        """
        __deepcopy__() should copy all attributes properly (#25085).
        """
        widget = Select()
        obj = copy.deepcopy(widget)
        self.astertIsNot(widget, obj)
        self.astertEqual(widget.choices, obj.choices)
        self.astertIsNot(widget.choices, obj.choices)
        self.astertEqual(widget.attrs, obj.attrs)
        self.astertIsNot(widget.attrs, obj.attrs)

3 View Complete Implementation : test_models.py
Copyright GNU Affero General Public License v3.0
Author : project-callisto
    def test_can_make_dropdown(self):
        model = models.Dropdown.objects.create(text="this is a dropdown")
        for i in range(5):
            Choice.objects.create(text=f"choice {i}", question=model)
        mock = mocks.MockQuestion(model.serialized)
        field = mock.make_field()
        self.astertEqual(len(field.choices), 5)
        self.astertEqual(field.choices[3][1], "choice 3")
        self.astertIsInstance(field.widget, forms.Select)

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_clast=ErrorList,
                 label_suffix=None, empty_permitted=False, **kwargs):
        super(ReportFormWithSeries, self).__init__(data, files, auto_id, prefix, initial, error_clast, label_suffix,
                                                   empty_permitted, **kwargs)
        self.fields['time_series_pattern'].wiget = forms.Select(choices=(('none', _('None')), ('daily', _('Daily')),
                                                                         ('monthly', _('Monthly'))))

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def __init__(self, *args, **kwargs):
        super(ClientRestrictionsInformation, self).__init__(*args, **kwargs)

        for day, translation in DAYS_OF_WEEK:
            self.fields['size_{}'.format(day)] = forms.ChoiceField(
                choices=SIZE_CHOICES,
                widget=forms.Select(),
                required=False
            )

            for meal, meal_translation in COMPONENT_GROUP_CHOICES:
                if meal is COMPONENT_GROUP_CHOICES_SIDES:
                    continue  # skip "Sides"
                self.fields['{}_{}_quansaty'.format(meal, day)] = \
                    forms.IntegerField(
                        required=False,
                        min_value=0,
                        widget=forms.TextInput()
                    )

3 View Complete Implementation : task_template.py
Copyright MIT License
Author : telminov
    def __init__(self, current_user, *args, **kwargs):
        self.user = current_user
        super().__init__(*args, **kwargs)
        self.fields['ansible_user'].initial = models.AnsibleUser.objects.first()
        self.fields['playbook'] = forms.FilePathField(path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$',
                                                      widget=forms.Select(attrs={'clast': 'need-select2'}))
        self.fields['hosts'].queryset = models.Host.objects.filter(users__in=[self.user, ])

3 View Complete Implementation : beer_forms.py
Copyright MIT License
Author : thorrak
    def __init__(self, *args, **kwargs):
        super(BeerCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['clast'] = "form-control"
        self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(),
                                                  widget=forms.Select(attrs={'clast': 'form-control',
                                                                             'data-toggle': 'select'}))

3 View Complete Implementation : device_forms.py
Copyright MIT License
Author : thorrak
    def __init__(self, *args, **kwargs):
        super(TempControlForm, self).__init__(*args, **kwargs)
        # for this_field in self.fields:
        #     self.fields[this_field].widget.attrs['clast'] = "form-control"
        self.fields['profile'] = forms.ChoiceField(required=False,
                                                   choices=self.get_profile_choices(),
                                                   widget=forms.Select(attrs={'clast': 'form-control'}))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : thorrak
    def __init__(self, *args, **kwargs):
        super(GravityLogCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['clast'] = "form-control"
        self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(),
                                                  widget=forms.Select(attrs={'clast': 'form-control',
                                                                             'data-toggle': 'select'}))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : thorrak
    def __init__(self, *args, **kwargs):
        super(SensorAttachForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['clast'] = "form-control"
        self.fields['sensor'] = forms.ChoiceField(required=True, choices=self.get_sensor_choices(),
                                                  widget=forms.Select(attrs={'clast': 'form-control',
                                                                             'data-toggle': 'select'}))
        self.fields['temp_controller'] = forms.ChoiceField(required=True, choices=self.get_controller_choices(),
                                                           widget=forms.Select(attrs={'clast': 'form-control',
                                                                                      'data-toggle': 'select'}))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : thorrak
    def __init__(self, *args, **kwargs):
        super(TiltCreateForm, self).__init__(*args, **kwargs)
        for this_field in self.fields:
            self.fields[this_field].widget.attrs['clast'] = "form-control"
        self.fields['tiltbridge'] = forms.ChoiceField(required=False, choices=self.get_tiltbridge_choices(),
                                                      widget=forms.Select(attrs={'clast': 'form-control',
                                                                                 'data-toggle': 'select'}))

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def __init__(self, group, *args, **kwargs):
        super(AccountAddForm, self).__init__(*args, **kwargs)
        if group:
            query = Account.objects.exclude(id__in=group.accounts.all())
        else:
            query = Account.objects.all()

        self.fields['account'] = forms.models.ModelChoiceField(
            query, required=True, widget=forms.Select(), label='')

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('account', css_clast='select2'),
            Submit('submit_account', 'Add to group', css_clast='postfix')
        )

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
    def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)
        creating = not self.instance.pk

        if hasattr(self.instance, 'author_id'):
            if self.instance.author_id is None:
                self.instance.author = request.user

        if 'geometry' in self.fields:
            if not geometry_editable:
                # can't see this geometry in editor
                self.fields.pop('geometry')
            else:
                # hide geometry widget
                self.fields['geometry'].widget = HiddenInput()
                if not creating:
                    self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':'))

        if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser:
            Source = self.request.changeset.wrap_model('Source')

            sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id',
                                                                         'left', 'bottom', 'right', 'top')}
            used_names = set(sources.keys())
            all_names = set(os.listdir(settings.SOURCES_ROOT))
            if not creating:
                used_names.remove(self.instance.name)
                all_names.add(self.instance.name)
            self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names)))

            if creating:
                for s in sources.values():
                    s['access_restriction'] = s['access_restriction_id']
                    del s['access_restriction_id']
                self.fields['copy_from'] = ChoiceField(
                    choices=tuple((('', '---------'), ))+tuple(
                        (json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name)
                        for name in sorted(used_names)
                    ),
                    required=False
                )

            self.fields['fixed_x'] = DecimalField(label='fixed x', required=False,
                                                  max_digits=7, decimal_places=3, initial=0)
            self.fields['fixed_y'] = DecimalField(label='fixed y', required=False,
                                                  max_digits=7, decimal_places=3, initial=0)
            self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False,
                                                  max_digits=7, decimal_places=3, initial=1)
            self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False,
                                                  max_digits=7, decimal_places=3, initial=1)
            self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True)
            self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True)

            self.fields.move_to_end('lock_scale', last=False)
            self.fields.move_to_end('lock_aspect', last=False)
            self.fields.move_to_end('scale_y', last=False)
            self.fields.move_to_end('scale_x', last=False)
            self.fields.move_to_end('fixed_y', last=False)
            self.fields.move_to_end('fixed_x', last=False)
            self.fields.move_to_end('access_restriction', last=False)
            if creating:
                self.fields.move_to_end('copy_from', last=False)
            self.fields.move_to_end('name', last=False)

        if self._meta.model.__name__ == 'AccessRestriction':
            AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup')

            self.fields['groups'].label_from_instance = lambda obj: obj.satle
            self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request)

        elif 'groups' in self.fields:
            LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory')

            kwargs = {'allow_'+self._meta.model._meta.default_related_name: True}
            categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups')
            if self.instance.pk:
                instance_groups = tuple(self.instance.groups.values_list('pk', flat=True))
            else:
                instance_groups = ()

            self.fields.pop('groups')

            for category in categories:
                choices = tuple((str(group.pk), group.satle)
                                for group in sorted(category.groups.all(), key=self.sort_group))
                category_groups = set(group.pk for group in category.groups.all())
                initial = tuple(str(pk) for pk in instance_groups if pk in category_groups)
                if category.single:
                    name = 'group_'+category.name
                    initial = initial[0] if initial else ''
                    choices = (('', '---'), )+choices
                    field = ChoiceField(label=category.satle, required=False, initial=initial, choices=choices,
                                        help_text=category.help_text)
                else:
                    name = 'groups_'+category.name
                    field = MultipleChoiceField(label=category.satle_plural, required=False,
                                                initial=initial, choices=choices,
                                                help_text=category.help_text)
                self.fields[name] = field

            if 'label_settings' in self.fields:
                self.fields.move_to_end('label_settings')

            for field in tuple(self.fields.keys()):
                if field.startswith('label_override'):
                    self.fields.move_to_end(field)

        if 'category' in self.fields:
            self.fields['category'].label_from_instance = attrgetter('satle')

        if 'label_settings' in self.fields:
            self.fields['label_settings'].label_from_instance = attrgetter('satle')

        if 'access_restriction' in self.fields:
            AccessRestriction = self.request.changeset.wrap_model('AccessRestriction')

            self.fields['access_restriction'].label_from_instance = lambda obj: obj.satle
            self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request)

        if 'base_mapdata_accessible' in self.fields:
            if not request.user.is_superuser:
                self.fields['base_mapdata_accessible'].disabled = True

        if space_id and 'target_space' in self.fields:
            Space = self.request.changeset.wrap_model('Space')

            GraphNode = self.request.changeset.wrap_model('GraphNode')
            GraphEdge = self.request.changeset.wrap_model('GraphEdge')

            cache_key = 'editor:neighbor_spaces:%s:%s%d' % (
                self.request.changeset.raw_cache_key_by_changes,
                AccessPermission.cache_key_for_request(request, with_update=False),
                space_id
            )
            other_spaces = cache.get(cache_key, None)
            if other_spaces is None:
                AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0)
                space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True))
                space_edges = GraphEdge.objects.filter(
                    Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes)
                ).values_list('from_node_id', 'to_node_id')
                other_nodes = set(chain(*space_edges)) - space_nodes
                other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True))
                other_spaces.discard(space_id)
                cache.set(cache_key, other_spaces, 900)

            for space_field in ('origin_space', 'target_space'):
                other_space_id = getattr(self.instance, space_field+'_id', None)
                if other_space_id:
                    other_spaces.add(other_space_id)

            space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces)

            for space_field in ('origin_space', 'target_space'):
                if space_field in self.fields:
                    self.fields[space_field].label_from_instance = lambda obj: obj.satle
                    self.fields[space_field].queryset = space_qs

        self.redirect_slugs = None
        self.add_redirect_slugs = None
        self.remove_redirect_slugs = None
        if 'slug' in self.fields:
            self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True))
            self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma seperated)'), required=False,
                                                      initial=','.join(self.redirect_slugs))
            self.fields.move_to_end('redirect_slugs', last=False)
            self.fields.move_to_end('slug', last=False)

        if 'from_node' in self.fields:
            self.fields['from_node'].widget = HiddenInput()

        if 'to_node' in self.fields:
            self.fields['to_node'].widget = HiddenInput()

        if 'data' in self.fields and 'data' in self.initial:
            self.initial['data'] = json.dumps(self.initial['data'])

        self.is_json = is_json
        self.missing_fields = tuple((name, field) for name, field in self.fields.items()
                                    if name not in self.data and not field.required)

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : chrisjrn
    @clastmethod
    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.QUANsatY_FIELD] = forms.IntegerField(
            label="Quansaty",  # TODO: internationalise
            min_value=0,
            max_value=500,  # Issue #19. We should figure out real limit.
        )

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, *args, **kwargs):
        super(QueryByExampleForm, self).__init__(*args, **kwargs)
        model_widget = forms.Select(attrs={'clast': "qbeFillModels to:field"})
        self.fields['model'].widget = model_widget
        sort_widget = forms.Select(attrs={'disabled': "disabled",
                                          'clast': 'submitIfChecked'},
                                   choices=SORT_CHOICES)
        self.fields['sort'].widget = sort_widget
        criteria_widget = CriteriaInput(attrs={'disabled': "disabled"})
        self.fields['criteria'].widget = criteria_widget
        criteria_widgets = getattr(criteria_widget, "widgets", [])
        if criteria_widgets:
            criteria_len = len(criteria_widgets)
            criteria_names = ",".join([("criteria_%s" % s)
                                       for s in range(0, criteria_len)])
            field_attr_clast = "qbeFillFields enable:sort,%s" % criteria_names
        else:
            field_attr_clast = "qbeFillFields enable:sort,criteria"
        field_widget = forms.Select(attrs={'clast': field_attr_clast})
        self.fields['field'].widget = field_widget

0 View Complete Implementation : forms.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
    def __init__(self, attrs=None):
        self.time_clast = "timepicker"
        if not attrs:
            attrs = {}
        if "time_clast" in attrs:
            self.time_clast = attrs.pop("time_clast")
        if "clast" not in attrs:
            attrs["clast"] = "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)

0 View Complete Implementation : admin.py
Copyright BSD 2-Clause "Simplified" License
Author : GetTogetherComm
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["view"].widget = forms.Select(choices=url_choices())

0 View Complete Implementation : crispy_forms_bulma_field.py
Copyright MIT License
Author : jhotujec
@register.filter
def is_select(field):
    return isinstance(field.field.widget, forms.Select)

0 View Complete Implementation : test_select.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_constructor_generator(self):
        """
        If choices is pasted 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>"""
        ))

0 View Complete Implementation : test_textfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_generates_select_widget(self):
        """A TextField with choices uses a Select widget."""
        f = models.TextField(choices=[('A', 'A'), ('B', 'B')])
        self.astertIsInstance(f.formfield().widget, forms.Select)

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def __init__(self, *args, **kwargs):
        self.base_fields['content_type'] = forms.ChoiceField(choices=get_ra_relevant_content_types(),
                                                             widget=forms.Select())
        super(CtCheckForm, self).__init__(*args, **kwargs)

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def __init__(self, *args, **kwargs):
        self.base_fields['content_type'] = forms.ChoiceField(choices=get_ra_relevant_content_types(),
                                                             widget=forms.Select())
        super(CtReverseCheckForm, self).__init__(*args, **kwargs)

0 View Complete Implementation : form_factory.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
def report_form_factory(model, base_model=None,
                        admin=True, magic_fields_filer_func=None,
                        fkeys_filter_func=None, doc_types_filter_func=None,
                        **kwargs):
    '''

    '''

    fkeys_filter_func = fkeys_filter_func or (lambda x: x)
    magic_fields_filer_func = magic_fields_filer_func or (lambda x: x)
    doc_types_filter_func = doc_types_filter_func or (lambda x: x)

    magic_fields = field_registry.get_all_report_fields_names()
    magic_fields = magic_fields_filer_func(magic_fields)

    fields = OrderedDict()
    base_model_list = []
    fkeys_list = []

    if base_model is not None:
        if type(base_model) is str:
            base_model_name = base_model
        else:
            base_model_name = base_model.__name__.lower()
        base_model_list.append(base_model_name)

    time_series_options = ['daily', 'weekly', 'semimonthly', 'monthly', 'quarterly', 'semiannually', 'annually']

    doc_types_raw = base_model.get_doc_types()
    doc_types_raw = doc_types_filter_func(doc_types_raw)
    doc_types_magical_field = ['__doc_type_%s__' % doc for doc in list(doc_types_raw)]

    magic_fields += doc_types_magical_field

    fkeys_map = get_foreign_keys(model)
    fkeys_map = fkeys_filter_func(fkeys_map)

    _movmenet_fields = get_model_fields2(model, all_fields=True, no_recurse=False,
                                         recurse_name_slug_only=True, exclude_movement=True)  # get_id_and_slug=True
    magic_fields_ordered = apply_order_to_list(magic_fields,
                                               ['__fb__', '__debit__', '__credit__', '__total__', '__balance__',
                                                '__last_doc_date__', '__doc_count__', '__line_count__'])

    fk_choices = [(k.replace('_id', ''), v.verbose_name) for k, v in fkeys_map.items()]

    scopes = choices_from_list(['group', 'details', 'both'], False)
    if admin:

        fields['group_by'] = forms.ChoiceField(required=False, widget=forms.Select(),
                                               choices=fk_choices + [('doc_type', _('doc_type'))],
                                               label=_('group by'))
        _grp_display = ['slug', 'satle'] + magic_fields

        default_for_group_display = ['slug', 'satle', '__fb__', '__debit__', '__credit__', '__balance__']
        fields['group_columns'] = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple(),
                                                            choices=choices_from_list(_grp_display, False) +
                                                                    choices_from_list(_movmenet_fields, False,
                                                                                      extra_list=magic_fields_ordered),
                                                            initial=default_for_group_display,
                                                            label=ugettext_lazy('group_columns'))

        fields['aggregate_on'] = forms.ChoiceField(required=False, widget=forms.Select(),
                                                   choices=[('', '----'), ] + fk_choices,
                                                   label=ugettext_lazy('aggregate_on'))

        default_display = list(_movmenet_fields)
        try:
            default_display.remove('creation_date')
            default_display.remove('lastmod')
        except ValueError:
            past

        default_display += ['__fb__', '__debit__', '__credit__', '__balance__']
        fields['details_columns'] = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple(),
                                                              choices=choices_from_list(_movmenet_fields, False,
                                                                                        extra_list=magic_fields_ordered),
                                                              initial=default_display, label=_('details_columns'))

        time_series_options = choices_from_list(time_series_options)
        default_for_time_series = ['__balance__']  # todo: fix Bug __last_doc_date__
        fields['time_series_pattern'] = forms.ChoiceField(choices=time_series_options,
                                                          widget=forms.Select(), required=False,
                                                          label=_('time series pattern'))

        fields['time_series_fields'] = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple(),
                                                                 choices=choices_from_list(magic_fields, False),
                                                                 label=_('time series fields'),
                                                                 initial=default_for_time_series)

        fields['time_series_display'] = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple(),
                                                                  choices=choices_from_list(magic_fields, False),
                                                                  label=_('details time series display'),
                                                                  initial=default_for_time_series)

        fields['time_series_scope'] = forms.ChoiceField(required=False, widget=forms.Select,
                                                        choices=scopes, label=_('time series scope'), initial='group')

        movement_or_balance_choices = choices_from_list(['balance', 'movement'], False)
        fields['movement_or_balance'] = forms.ChoiceField(required=False, widget=forms.Select,
                                                          label=_('computation type'),
                                                          choices=movement_or_balance_choices, initial='movement')

        fields['doc_types'] = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(),
                                                        choices=choices_from_list(doc_types_raw,
                                                                                  append_none=False),
                                                        initial=doc_types_raw,
                                                        label=_('doc types'))

        fields['group_col_order'] = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput)
        fields['details_col_order'] = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput)
        fields['print_group_satle'] = forms.CharField(max_length=50, required=False, label=_('print group satle'))
        fields['print_details_satle'] = forms.CharField(max_length=50, required=False, label=_('print details satle'))

        fields['custom_group_column_names'] = forms.CharField(max_length=10000, required=False,
                                                              label=_('Custom group column names'))
        fields['custom_details_column_names'] = forms.CharField(max_length=10000, required=False,
                                                                label=_('Custom details column names'))

    fields['from_doc_date'] = RaDateDateTimeField(required=False, label=capfirst(ugettext_lazy('from date')),
                                                  initial=app_settings.DEFAULT_FROM_DATE_TIME,
                                                  widget=RaBootstrapDateTime(),
                                                  input_date_formats=['%Y-%m-%d', '%Y-%m-%d'],
                                                  input_time_formats=['%H:%M', '%H:%M:%S'])

    to_date_initial = datetime.datetime.combine(now().date() + datetime.timedelta(days=1), datetime.time.min)
    fields['to_doc_date'] = RaDateDateTimeField(required=False, initial=to_date_initial,
                                                label=capfirst(ugettext_lazy('to date')), widget=RaBootstrapDateTime(),
                                                input_date_formats=['%Y-%m-%d', '%Y-%m-%d'],
                                                input_time_formats=['%H:%M', '%H:%M:%S'])

    fields['can_edit_primary_index'] = forms.BooleanField(required=False, initial=False,
                                                          label=_('can edit primary index'))
    fields['can_edit_secondary_index'] = forms.BooleanField(required=False, initial=False,
                                                            label=_('can edit secondary index'))
    fields['can_edit_time_series_pattern'] = forms.BooleanField(required=False, initial=False,
                                                                label=_('can edit timeseries pattern'))
    fields['can_edit_doc_types'] = forms.BooleanField(required=False, initial=False, label=_('can edit doc_types'))
    fields['can_edit_matrix_ensaties'] = forms.BooleanField(required=False, initial=True,
                                                            label=_('can edit matrix ensaties'))

    fields['matrix'] = forms.ChoiceField(choices=[('', '----'), ] + fk_choices, label=_('matrix support'),
                                         required=False,
                                         widget=forms.Select())
    fields['matrix_columns'] = forms.MultipleChoiceField(choices=choices_from_list(magic_fields_ordered, False),
                                                         label=_('matirx fields'),
                                                         widget=forms.SelectMultiple, required=False,
                                                         initial=['__balance__'])

    fields['matrix_show_other'] = forms.BooleanField(required=False, widget=forms.CheckboxInput(),
                                                     label=_('Show [The rest]'), initial=True)
    fields['matrix_ensaties'] = forms.CharField(required=False, label=_('matrix ensaties'))

    fields['matrix_scope'] = forms.ChoiceField(required=False, widget=forms.Select,
                                               choices=scopes, label=_('matrix scope'), initial='both')

    for name, f_field in fkeys_map.items():
        fkeys_list.append(name)

        from ra.admin.admin import ra_admin_site

        fields[name] = f_field.formfield(
            **{'form_clast': forms.ModelMultipleChoiceField,
               'required': False,
               'widget': RaAutocompleteSelectMultiple(f_field.remote_field, ra_admin_site,
                                                      attrs={'clast': 'select2bs4'})})

    fields['doc_date'] = forms.DateField(input_formats=["%Y-%m-%d"], required=False, label=ugettext_lazy('at date'))

    fields['add_details_control'] = forms.BooleanField(required=False, initial=False)

    # Get_initial_form_settings
    initial_settings = {}
    for field in fields.keys():
        initial_settings[field] = fields[field].initial

    new_form = type('ReportForm', (BaseReportForm, forms.BaseForm,),
                    {"base_fields": fields,
                     '_fkeys': fkeys_list,
                     'initial_settings': initial_settings,
                     'base_model': base_model,
                     'foreign_keys': fkeys_map,
                     'magic_fields': magic_fields,
                     'docameent_report_fields': ['slug', 'doc_date', 'doc_type']
                     })

    return new_form

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def __init__(self, *args, **kwargs):
        if 'delivery_dates' in kwargs:
            delivery_dates = kwargs['delivery_dates']
            del kwargs['delivery_dates']
        else:
            delivery_dates = None
        super(CreateOrdersBatchForm, self).__init__(*args, **kwargs)

        if delivery_dates:
            for d in delivery_dates:
                self.fields['size_{}'.format(d)] = forms.ChoiceField(
                    choices=SIZE_CHOICES,
                    widget=forms.Select(attrs={'clast': ''}),
                    required=True
                )
                self.fields['delivery_{}'.format(d)] = forms.BooleanField(
                    required=False
                )
                self.fields['pickup_{}'.format(d)] = forms.BooleanField(
                    required=False
                )
                self.fields['visit_{}'.format(d)] = forms.BooleanField(
                    required=False
                )

                for meal, meal_translation in COMPONENT_GROUP_CHOICES:
                    if meal is COMPONENT_GROUP_CHOICES_SIDES:
                        continue  # don't put "sides" on the form
                    self.fields[
                        '{}_{}_quansaty'.format(meal, d)
                    ] = forms.IntegerField(
                        min_value=0,
                        required=True
                    )

0 View Complete Implementation : task.py
Copyright MIT License
Author : telminov
    def __init__(self, *args, **kwargs):
        super(Search, self).__init__(*args, **kwargs)
        self.fields['playbook'] = forms.FilePathField(path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$',
                                                      required=False, widget=forms.Select(attrs={'clast': 'need-select2'}))

0 View Complete Implementation : task.py
Copyright MIT License
Author : telminov
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['ansible_user'].initial = models.AnsibleUser.objects.first()
        self.fields['playbook'] = forms.FilePathField(path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$',
                                                      widget=forms.Select(attrs={'clast': 'need-select2'}))