Python django.forms 模块,Select() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.Select()

项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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__userprofile__organization=self.request.organization))
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True))
        self.fields['form'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['form'].empty_label = None
        self.fields['form'].label = "Select Form"
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
def set_choices(self, family):
        # There's probably a better way of doing this
        board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family=family)]

        self.fields['board_type'].choices = board_choices


# class GuidedDeviceFlashForm(forms.Form):
#     DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES
#
#     device_family = forms.ChoiceField(label="Device Family",
#                                       widget=forms.Select(attrs={'class': 'form-control',
#                                                                  'data-toggle': 'select'}),
#                                       choices=DEVICE_FAMILY_CHOICES, required=True)
#     should_flash_device = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False)
#
#
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [
            """<div%(attrs)s>"""
            """    <button class="btn btn-group-label%(disabled)s" type="button">%(label)s</button>"""
            """    <button class="btn btn-default dropdown-toggle%(disabled)s" type="button" data-toggle="dropdown">"""
            """        <span class="caret"></span>"""
            """    </button>"""
            """    <ul class="dropdown-menu">"""
            """        %(options)s"""
            """    </ul>"""
            """    <input type="hidden" name="%(name)s" value="" class="btn-group-value" />"""
            """</div>"""
            """<noscript>%(noscript)s</noscript>""" %
            {'attrs': flatatt(final_attrs),
             'options': self.render_options(choices, [value]),
             'label': _('Select an option'),
             'name': name, 'disabled': ' disabled' if self.disabled else '',
             'noscript': self.noscript_widget.render(name, value, {})}]
        return mark_safe('\n'.join(output))
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def __init__(self, choices, validators, *args, **kwargs):
        """
        :param validators:  A dict that maps query type
        values to validators.
        """
        if validators is None:
            validators = {}
        super(MultitypeQueryField, self).__init__(*args, **kwargs)
        self.fields = (
            forms.ChoiceField(choices=choices),
            forms.CharField(min_length=1)
        )
        self.widget = MultitypeQueryWidget(
            (forms.Select(choices=choices),
             forms.TextInput())
        )
        self.query_validators = validators
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def _get_form_widgets(self):
        """
        Returns a dict of form widgets keyed by field name

        :return: Dict of field widgets
        """
        widgets = super(OmniModelFormFieldView, self)._get_form_widgets()
        widgets.update({
            'name': forms.HiddenInput,
            'widget_class': forms.HiddenInput,
        })

        if self._field_is_required:
            widgets['required'] = forms.HiddenInput

        if issubclass(self.model, OmniRelatedField):
            widgets['related_type'] = forms.HiddenInput

        if len(self.model.FORM_WIDGETS) > 1:
            choices = map(lambda x: (x, x.rsplit('.')[-1]), self.model.FORM_WIDGETS)
            widgets['widget_class'] = forms.Select(choices=choices)

        return widgets
项目:Kiwi    作者:kiwitcms    | 项目源码 | 文件源码
def __init__(self, attrs=None):
        self.widgets = []
        if not attrs:
            attrs = {}
        inputs = attrs.get('inputs', self.INPUTS)
        multiply = []
        for input in inputs:
            assert input in self.INPUTS, (input, self.INPUT)
            self.widgets.append(
                forms.Select(
                    attrs=attrs,
                    choices=getattr(
                        self,
                        'ESTIMATED_' + input.upper() + '_CHOICE'
                    )
                )
            )
            multiply.append(self.MULTIPLY[self.INPUTS.index(input)])
        self.inputs = inputs
        self.multiply = multiply
        super(TimedeltaWidget, self).__init__(attrs)
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
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.
        )
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
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
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def formfield(self, form_class=None, **kwargs):
        if form_class is None:
            form_class = self.form_field_class
        kwargs['form_class'] = form_class
        kwargs['widget'] = forms.Select
        return super(BaseRegistryItemField, self).formfield(**kwargs)
项目:openbare    作者:openbare    | 项目源码 | 文件源码
def is_dropdown(field):
    """Check if instance of Select widget."""
    return isinstance(field.field.widget, forms.Select)
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def init_chosen_widget(field_items, disable_help_text=True):
    """
    Add ``.chosen-widget`` html class attribute to all fields of type ``Select`` or ``SelectMultiple``.

    :param field_items: Django field items
    :param bool disable_help_text: Disable the fields help text. Default: True
    """
    for name, field in field_items:
        if isinstance(field.widget, SelectMultiple) or isinstance(field.widget, Select):
            field.widget.attrs['class'] = 'chosen-widget'
            # field.widget.attrs['style'] = 'width: 100%;'
            if disable_help_text:
                field.help_text = None
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def is_select(field):
    return isinstance(field.field.widget, forms.Select)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def make_reorder_languagelist_form(objlist):
    choices = [(e.id, e.ascii_name) for e in objlist]

    class ReorderLanguageListForm(forms.Form):
        language = forms.ChoiceField(
            choices=choices,
            widget=forms.Select(attrs={"size": 20}))
    return ReorderLanguageListForm
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def make_reorder_meaninglist_form(objlist):
    choices = [(e.id, e.gloss) for e in objlist]

    class ReorderMeaningListForm(forms.Form):
        meaning = forms.ChoiceField(
            choices=choices,
            widget=forms.Select(attrs={"size": 20}))
    return ReorderMeaningListForm
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('obj')
        self.model = self.instance.__class__

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

        self.fields['of'] = forms.ModelChoiceField(
            label=pgettext('MoveForm', 'Of'),
            required=False,
            queryset=self.model.objects.exclude(
                pk__in=self.instance.descendants(),
            ),
            widget=forms.Select(attrs={'size': 30, 'style': 'height:auto'}),
        )

        self.fields['of'].choices = [
            (None, '----------'),
        ] + [
            (
                obj.pk,
                '%s%s' % (
                    (obj.depth - 1) * (
                        '*** ' if obj == self.instance else '--- '),
                    obj,
                ),
            ) for obj in self.fields['of'].queryset
        ]
项目:callisto-core    作者: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.assertEqual(len(field.choices), 5)
        self.assertEqual(field.choices[3][1], "choice 3")
        self.assertIsInstance(field.widget, forms.Select)
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def __init__(self, task, *args, **kwargs):
        super(ChoiceAnswerForm, self).__init__(*args, **kwargs)
        if task:
            qs = task.choices
            widget = forms.RadioSelect
            empty_label = None
            count = task.no_of_choices
            if count > settings.TASK_CHOICE_SELECT_CUTOFF:
                widget = forms.Select
                empty_label = BLANK_CHOICE_DASH[0][1]
            self.fields['answer'] = forms.ModelChoiceField(queryset=qs,
                                                           widget=widget,
                                                           empty_label=empty_label)
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, *args, **kwargs):
        super(SelectSpyForm, self).__init__(*args, **kwargs)

        spies = list(Spy.objects.filter(owner=world, location=world))

        SPY_CHOICES = [(spy.pk, spy.name) for spy in spies]

        self.fields["spyselect"] = forms.IntegerField(widget=forms.Select(choices=SPY_CHOICES), label="Select Spy")
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, logtype, *args, **kwargs):
        super(DeleteByTargetForm, self).__init__(*args, **kwargs)

        if logtype == 'war':
            listlogs = Warlog.objects.filter(owner=world)

            listtargets = []
            for log in listlogs:
                if log.target not in listtargets:
                    listtargets.append(log.target)

        elif logtype == 'res':
            listlogs = ResourceLog.objects.filter(owner=world)

            listtargets = []
            for log in listlogs:
                if log.target not in listtargets:
                    listtargets.append(log.target)

        elif logtype == 'reccomm':
            listlogs = Comm.objects.filter(target=world)

            listtargets = []
            for log in listlogs:
                if log.sender not in listtargets:
                    listtargets.append(log.sender)

        elif logtype == 'sentcomm':
            listlogs = SentComm.objects.filter(sender=world)

            listtargets = []
            for log in listlogs:
                if log.target not in listtargets:
                    listtargets.append(log.target)

        TARGET_CHOICES = [(target.pk, target.name) for target in listtargets]

        self.fields["target"] = forms.IntegerField(widget=forms.Select(choices=TARGET_CHOICES), label="Select World")
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, shiptype, *args, **kwargs):
        super(PersonalShipPicForm, self).__init__(*args, **kwargs)

        if shiptype == 1:
            PSPIC_CHOICES = [('pf01','1'),
                             ('pf02','2'),
                             ('pf03','3'),
                             ('pf04','4'),
                             ('pf05','5'),
                             ('pf06','6'),
                             ('pf07','7'),
                             ('pf08','8'),
                             ('pf09','9'),
                             ('pf10','10')]

        elif shiptype == 2:
            PSPIC_CHOICES = [('my01','1'),
                             ('my02','2'),
                             ('my03','3'),
                             ('my04','4'),
                             ('my05','5'),
                             ('my06','6'),
                             ('my07','7'),
                             ('my08','8'),
                             ('my09','9'),
                             ('my10','10')]

        else:
            PSPIC_CHOICES = [('cs01','1'),
                             ('cs02','2'),
                             ('cs03','3'),
                             ('cs04','4'),
                             ('cs05','5'),
                             ('cs06','6'),
                             ('cs07','7'),
                             ('cs08','8'),
                             ('cs09','9'),
                             ('cs10','10')]

        self.fields["pspic"] = forms.CharField(max_length=4, widget=forms.Select(choices=PSPIC_CHOICES, attrs={'id':'pspicchoice'}),
            label="Ship Picture")
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, pk, *args, **kwargs):
        super(trainfleetform, self).__init__(*args, **kwargs)
        query = fleet.objects.filter(world=pk).exclude(sector='hangar')
        query = query.exclude(sector='warping')
        self.fields['fleet'] = forms.ModelChoiceField(queryset=query, 
            label="Fleet to train", widget=forms.Select(attrs={'id': 'trainchoice', 'onchange': 'trainfleetcost()'}))
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, *args, **kwargs):
        super(fleetwarpform, self).__init__(*args, **kwargs)
        query = fleet.objects.filter(controller=world).exclude(sector="hangar").exclude(sector="warping")
        choices = []
        for sfleet in query:
            choices.append((sfleet.pk, sfleet.name + " - " + sfleet.sector))
        choices = tuple(choices)
        self.fields['fleet'] = forms.ChoiceField(choices=choices, label="Select fleet to warp")
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def __init__(self, attrs=None):
        choices = (('1', '-'), ('2', _('Yes')), ('3', _('No')))
        forms.widgets.Select.__init__(self, attrs, choices)
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        queryset = User.objects.filter(groups__name='Userswitcher Target', is_active=True).select_related('profile').order_by('last_name', 'first_name', 'email')
        defaults = {
            'required': False,
            'widget': forms.Select(attrs={'id': 'userswitcher_input'}),
        }
        for k, v in defaults.items():
            kwargs.setdefault(k, v)
        super().__init__(queryset, *args, **kwargs)
项目:esdc-ce    作者: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()]
        )
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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'))
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
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
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
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'}))
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
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'}))
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
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'}))
项目:ansible-manager    作者: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={'class': 'need-select2'}))
项目:ansible-manager    作者: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={'class': 'need-select2'}))
项目:ansible-manager    作者: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={'class': 'need-select2'}))
项目:sadm    作者:prologin    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MatchCreationForm, self).__init__(*args, **kwargs)
        self.helper = BaseFormHelper()
        self.champions = []
        champions = (models.Champion.objects
                           .filter(deleted=False, status='ready')
                           .select_related('author'))
        if (settings.STECHEC_FIGHT_ONLY_OWN_CHAMPIONS and not
            self.request.user.is_staff):
            champions = champions.filter(author=self.request.user)
        for i in range(1, settings.STECHEC_NPLAYERS + 1):
            f = forms.ModelChoiceField(label="Champion %d" % i,
                                       queryset=champions,
                                       widget=forms.Select(attrs={'class': 'select2'}))
            self.fields['champion_%d' % i] = f
            self.helper.append_field('champion_%d' % i)
            self.champions.append(f)

        if settings.STECHEC_USE_MAPS:
            self.fields['map'] = forms.ChoiceField(required=True,
                                                   widget=MapSelect(attrs={'class': 'mapselect select2'}),
                                                   label="Carte utilisée")

            all_maps = models.Map.objects.select_related('author').order_by('author__username', 'name')
            self.fields['map'].choices = [
                ('Officielles', [(map.id, map) for map in all_maps if map.official])
            ] + [
                (author, [(map.id, map) for map in maps])
                for author, maps in groupby(
                    (map for map in all_maps if not map.official),
                    lambda map: map.author
                )
            ]
            self.helper.append_field('map')

        self.helper.append_submit("Lancer le match")
项目:djangoshop-shopit    作者:dinoperovic    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.field_order = ['existant']  # Place `existant` field at the top.
        super(AddressForm, self).__init__(*args, **kwargs)
        self.customer = Customer.objects.get_from_request(self.request)

        # Set existant addresses choices.
        addresses = self.Meta.model.objects.filter(customer=self.customer).order_by('-priority')
        self.fields['existant'].queryset = addresses
        if not addresses.exists():
            self.fields['existant'].widget = forms.HiddenInput()

        # Set country choices based on `ADDRESS_COUNTRIES` setting.
        if ADDRESS_COUNTRIES:
            countries = [('', '---------')] + [x for x in ISO_3166_CODES if x in ADDRESS_COUNTRIES]
            self.fields['country'].widget = forms.Select(choices=countries)
            self.fields['country'].choices = countries

        assert PRIMARY_ADDRESS in ['shipping', 'billing'], "PRIMARY_ADDRESS must be either 'shipping' or 'billing'."
        if self.is_primary:
            self.fields.pop('use_primary_address')  # remove field from primary address.
        else:
            self.fields['use_primary_address'].initial = \
                getattr(self.cart, '%s_address' % self.address_type, None) is None
            if hasattr(self, 'use_primary_address_label'):
                self.fields['use_primary_address'].label = self.use_primary_address_label

        # If current address is set to the cart, use it as existant one.
        cart_address = getattr(self.cart, '%s_address' % self.address_type, None)
        if cart_address:
            self.fields['existant'].initial = cart_address
            for fname in [f.name for f in cart_address._meta.get_fields() if f.name in self.fields]:
                self.fields[fname].initial = getattr(cart_address, fname, '')
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        try:
            filter_master_bool = kwargs.pop('filter_master_bool')
        except KeyError:
            filter_master_bool = True
        super(PersonalTerritorySelects, self).__init__(*args, **kwargs)
        if filter_master_bool:
            self.fields['include_exclude'] = forms.ChoiceField(
                choices = (('filter',
                            "Filter (exclude values that don't match)"),
                           ('add', 'Add to List'),
                           ('exclude', 'Exclude from list'),),
                widget=forms.Select(
                    attrs={'class': 'form-control'}
                ),
            )
        else:
            self.fields['include_exclude'] = forms.ChoiceField(
                choices = (('add', 'Add to List'),
                           ('exclude', 'Exclude from list'),),
                widget=forms.Select(
                    attrs={'class': 'form-control'}
                ),
            )
        del filter_master_bool
        set_field_html_name(self.fields['geo'], 'geo_peronal')
        set_field_html_name(self.fields['main_category'],
                            'main_category_peronal')
        set_field_html_name(self.fields['main_category2'],
                            'main_category2_personal')
        set_field_html_name(self.fields['company'], 'company_personal')
        set_field_html_name(self.fields['industry'], 'industry_personal')
        set_field_html_name(self.fields['include_exclude'],
                            'include_exclude_personal')
        set_field_html_name(self.fields['dept'], 'dept_personal')
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(VenueForm, self).__init__(*args, **kwargs)
        self.fields['state_prov'] = forms.ChoiceField(
            choices=STATE_PROV_TUPLE,
            widget=forms.Select(
                attrs={'class': 'form-control'}
            ),
            initial='ON',
        )
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        # pop kwargs before super
        super(FieldSelectorForm, self).__init__(*args, **kwargs)
        self.fields['field_option'] = forms.ChoiceField(
            choices = self._person_model_fields,
            initial='',
            widget=forms.Select(
                attrs={'class': 'form-control pull-left'}
            )
        )
项目:cyphon    作者:dunbarcyber    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        backend = kwargs.pop('backend', None)
        database = kwargs.pop('database', None)
        collection = kwargs.pop('collection', None)
        super(CollectionQueryForm, self).__init__(*args, **kwargs)

        if backend and database and collection:

            # TODO(LH): provide contingency if no Distillery is associated with
            # the warehouse
            distillery = Distillery.objects.get_by_natural_key(backend, database,
                                                               collection)
            field_choices = self._get_field_choices(distillery.bottle)
            operator_choices = self._get_operator_choices()

            self.fields['datafield'] = forms.ChoiceField(
                choices=field_choices,
                label='Field name',
                widget=forms.Select(
                    attrs={'class': 'field'},
                )
            )

            self.fields['operator'] = forms.ChoiceField(
                choices=operator_choices,
                widget=forms.Select(
                    attrs={'class': 'operator'},
                )
            )

            self.fields['value'] = forms.CharField(
                required=False,
                widget=forms.TextInput(
                    attrs={'class': 'value'},
                )
            )
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def __init__(self, attrs={}, choices=(), disabled=False):
        attrs['class'] = 'btn-group pull-left btn-group-form'
        self.disabled = disabled
        self.noscript_widget = forms.Select(attrs={}, choices=choices)
        super(SelectWidgetBootstrap, self).__init__(attrs, choices)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def get_form_field(self, form_class=forms.CharField, **kwargs):
    """Return a Django form field appropriate for this property.

    Args:
      form_class: a forms.Field subclass, default forms.CharField

    Additional keyword arguments are passed to the form_class constructor,
    with certain defaults:
      required: self.required
      label: prettified self.verbose_name, if not None
      widget: a forms.Select instance if self.choices is non-empty
      initial: self.default, if not None

    Returns:
       A fully configured instance of form_class, or None if no form
       field should be generated for this property.
    """
    defaults = {'required': self.required}
    if self.verbose_name:
      defaults['label'] = self.verbose_name.capitalize().replace('_', ' ')
    if self.choices:
      choices = []
      if not self.required or (self.default is None and
                               'initial' not in kwargs):
        choices.append(('', '---------'))
      for choice in self.choices:
        choices.append((str(choice), unicode(choice)))
      defaults['widget'] = forms.Select(choices=choices)
    if self.default is not None:
      defaults['initial'] = self.default
    defaults.update(kwargs)
    return form_class(**defaults)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def __init__(self, reference_class, query=None, choices=None,
               empty_label=u'---------',
               required=True, widget=forms.Select, label=None, initial=None,
               help_text=None, *args, **kwargs):
    """Constructor.

    Args:
      reference_class: required; the db.Model subclass used in the reference
      query: optional db.Query; default db.Query(reference_class)
      choices: optional explicit list of (value, label) pairs representing
        available choices; defaults to dynamically iterating over the
        query argument (or its default)
      empty_label: label to be used for the default selection item in
        the widget; this is prepended to the choices
      required, widget, label, initial, help_text, *args, **kwargs:
        like for forms.Field.__init__(); widget defaults to forms.Select
    """
    assert issubclass(reference_class, db.Model)
    if query is None:
      query = db.Query(reference_class)
    assert isinstance(query, db.Query)
    super(ModelChoiceField, self).__init__(required, widget, label, initial,
                                           help_text, *args, **kwargs)
    self.empty_label = empty_label
    self.reference_class = reference_class

    self._query = query
    self._choices = choices
    self._update_widget_choices()
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def __init__(self, choices, validators={}, *args, **kwargs):
        """
        :param validators:  A dict that maps query type
        values to validators.
        """
        super(MultitypeQueryField, self).__init__(*args, **kwargs)
        self.fields = (
            forms.CharField(min_length=1),
            forms.ChoiceField(choices=choices)
        )
        self.widget = MultitypeQueryWidget(
            (forms.TextInput(),
             forms.Select(choices=choices))
        )
        self.query_validators = validators
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ServiceChoiceForm, self).__init__(*args, **kwargs)
        # NB: Setting the TextInput to hidden is done to display the label.
        #     The HiddenInput widget will remove the label
        self.fields['netbox'] = forms.CharField(
            label='IP Device',
            widget=forms.TextInput(attrs={'type': 'hidden'})
        )
        self.fields['service'] = forms.ChoiceField(
            choices=sorted(self._build_checker_choices()),
            widget=forms.Select(attrs={'class': 'select2'})
        )

        self.helper = FormHelper(self)
        self.helper.form_tag = False
项目:nav    作者: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_class='select2'),
            Submit('submit_account', 'Add to group', css_class='postfix')
        )
项目:slack-announcement-approval    作者:trianglefraternitymtu    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TeamSettingsForm, self).__init__(*args, **kwargs)

        slack = Slacker(kwargs['instance'].access_token)

        priv_ch = [(g['id'], g['name']) for g in slack.groups.list().body['groups'] if not (g['is_archived'] or g['name'].startswith('mpdm'))]
        pub_ch = [(c['id'], c['name']) for c in slack.channels.list().body['channels'] if not c['is_archived']]
        users = [(u['id'], u['profile']['real_name']) for u in slack.users.list().body['members'] if not u['deleted']]

        self.fields['post_channel'].widget = forms.Select(choices=tuple(pub_ch))
        self.fields['approval_channel'].widget = forms.Select(choices=tuple(pub_ch + priv_ch + users))
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def __init__(self, attrs=None, choices=()):
        super(Select, self).__init__(attrs)
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if self.attrs.get('readonly', False):
            self.attrs["disabled"] = True
            del self.attrs['readonly']
            return mark_safe('\n'.join(["<input type='hidden' name='{}' value='{}'>".format(name, value or ''), super(Select, self).render(name, value, attrs)]))
        else:
            if 'readonly' in self.attrs: del self.attrs['readonly']
            if 'disabled' in self.attrs: del self.attrs['disabled']
            return super(Select, self).render(name, value, attrs)
项目:django-wizard-builder    作者: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.assertEqual(len(field.choices), 5)
        self.assertEqual(field.choices[3][1], "choice 3")
        self.assertIsInstance(field.widget, forms.Select)
项目:django-timelines    作者:natgeosociety    | 项目源码 | 文件源码
def __init__(self, attrs=None):
        if attrs:
            new_attrs = attrs.copy()
        else:
            new_attrs = {'class': 'vHistoricDateField'}
        year_attrs = new_attrs.copy()
        year_attrs['size'] = "10"
        widgets = (forms.TextInput(attrs=year_attrs),
                   forms.Select(attrs=new_attrs, choices=(('-', 'BCE'), ('+', 'CE'))),
                   forms.Select(attrs=new_attrs, choices=get_month_choices()),
                   forms.Select(attrs=new_attrs, choices=get_day_choices()))
        return super(HistoricalDateWidget, self).__init__(widgets, attrs)