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

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

项目:stoicism    作者:srgpdbd    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        extra_field = kwargs.pop('extra')
        # create dict appropriate for MultipleChoiceField
        # like {question: [[option:option]]}
        extra_fields = {}
        for key in extra_field.keys():
            options = []
            # unpack QuerySet
            for answer_option in extra_field[key]:
                options.append((answer_option.option, answer_option.option))
            extra_fields[key] = options
        super(forms.Form, self).__init__(*args, **kwargs)
        for i, question in enumerate(extra_fields.keys()):
            # add answer options to fields
            self.fields['question_%s' % i] = forms.MultipleChoiceField(
                label=question,
                widget=forms.CheckboxSelectMultiple,
                choices=extra_fields[question]
                )
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def get_alert_types():
    """
    Creates a tuple structure of the alert types grouped by event types
    suitable for the choices of a MultipleChoiceField with optgroups
    [
      (event_type, [(alert_type, alert_type), (alert_type, alert_type)]),
      (event_type, [(alert_type, alert_type), (alert_type, alert_type)])
    ]

    """
    alert_types = defaultdict(list)
    for alert_type in AlertType.objects.all():
        alert_types[alert_type.event_type_id].append(
            (alert_type.name, alert_type.name))

    return sorted(alert_types.items(), key=itemgetter(0))
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def __init__(self, available_roles=[], *args, **kwargs):
        '''
        Custom logic to reduce the available permissions
        '''
        super(GymUserPermisssionForm, self).__init__(*args, **kwargs)

        field_choices = [(self.USER, _('User'))]
        if 'trainer' in available_roles:
            field_choices.append((self.TRAINER, _('Trainer')))
        if 'admin' in available_roles:
            field_choices.append((self.GYM_ADMIN, _('Gym administrator')))
        if 'manager' in available_roles:
            field_choices.append((self.MANAGER, _('General manager')))

        self.fields['role'] = forms.MultipleChoiceField(choices=field_choices,
                                                        initial=User,
                                                        widget=BootstrapSelectMultiple())
项目:wagtailsurveys    作者:torchbox    | 项目源码 | 文件源码
def test_fields(self):
        """
        This tests that all fields were added to the form with the correct types
        """
        form_class = self.fb.get_form_class()

        field_names = form_class.base_fields.keys()

        # All fields are present in form
        self.assertIn('your-name', field_names)
        self.assertIn('your-biography', field_names)
        self.assertIn('your-birthday', field_names)
        self.assertIn('your-birthtime', field_names)
        self.assertIn('your-email', field_names)
        self.assertIn('your-homepage', field_names)
        self.assertIn('your-favourite-number', field_names)
        self.assertIn('your-favourite-python-ides', field_names)
        self.assertIn('your-favourite-python-ide', field_names)
        self.assertIn('your-choices', field_names)
        self.assertIn('i-agree-to-the-terms-of-use', field_names)

        # All fields have proper type
        self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField)
        self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField)
        self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField)
        self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField)
        self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField)
        self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField)

        # Some fields have non-default widgets
        self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect)
        self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        defaults = {
            'form_class': forms.MultipleChoiceField,
            'choices': self.base_field.choices,
        }
        defaults.update(kwargs)
        return super(ArrayField, self).formfield(**defaults)
项目:django-daiquiri    作者:aipescience    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)

        # add a field for each detail key
        for detail_key in settings.AUTH_DETAIL_KEYS:

            choices = [(option['id'], option['label']) for option in detail_key['options']]

            if detail_key['data_type'] == 'text':
                field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'textarea':
                field = forms.CharField(widget=forms.Textarea(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'select':
                field = forms.ChoiceField(choices=choices)
            elif detail_key['data_type'] == 'radio':
                field = forms.ChoiceField(choices=choices, widget=forms.RadioSelect)
            elif detail_key['data_type'] == 'multiselect':
                field = forms.MultipleChoiceField(choices=choices)
            elif detail_key['data_type'] == 'checkbox':
                field = forms.MultipleChoiceField(choices=choices, widget=forms.CheckboxSelectMultiple)
            else:
                raise Exception('Unknown detail key data type.')

            if 'label' in detail_key:
                field.label = detail_key['label']

            if 'required' in detail_key:
                field.required = detail_key['required']

            if 'help_text' in detail_key:
                field.help_text = detail_key['help_text']

            if self.instance.details and detail_key['key'] in self.instance.details:
                field.initial = self.instance.details[detail_key['key']]

            self.fields[detail_key['key']] = field
项目:maas    作者:maas    | 项目源码 | 文件源码
def clean(self, value):
        """Clean the list of field values.

        Assert that each field value corresponds to an instance of the class
        `self.model_class`.
        """
        if value is None:
            return None
        # `value` is in fact a list of values since this field is a subclass of
        # forms.MultipleChoiceField.
        set_values = set(value)
        filters = {'%s__in' % self.field_name: set_values}

        instances = self.model_class.objects.filter(**filters)
        if len(instances) != len(set_values):
            unknown = set_values.difference(
                {getattr(instance, self.field_name) for instance in instances})
            error = self.text_for_invalid_object.format(
                obj_name=self.model_class.__name__.lower(),
                unknown_names=', '.join(sorted(unknown))
                )
            raise forms.ValidationError(error)
        return instances
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
def model_fields_form_factory(model):
    ''' Creates a form for specifying fields from a model to display. '''

    fields = model._meta.get_fields()

    choices = []
    for field in fields:
        if hasattr(field, "verbose_name"):
            choices.append((field.name, field.verbose_name))

    class ModelFieldsForm(forms.Form):
        fields = forms.MultipleChoiceField(
            choices=choices,
            required=False,
        )

    return ModelFieldsForm
项目:django-livesettings3    作者:kunaldeo    | 项目源码 | 文件源码
def choice_field(self, **kwargs):
        kwargs['required'] = False
        return forms.MultipleChoiceField(choices=self.choices, **kwargs)
项目:opencon-2016-app-code    作者:sparcopen    | 项目源码 | 文件源码
def __init__(self, choices, required=False, *args, **kwargs):
        self.required = required
        fields = [
            forms.MultipleChoiceField(choices=choices, widget=forms.widgets.CheckboxSelectMultiple, required=False),
            forms.CharField(required=False, widget=forms.TextInput, help_text='Other')
        ]
        self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields])
        super().__init__(required=False, fields=fields, *args, **kwargs)
项目:django-jsonattrs    作者:Cadasta    | 项目源码 | 文件源码
def add_attribute_fields(self, schema_selectors):
        attrs = None
        attrvals = getattr(self.instance, self.attributes_field)
        schemas = None
        if self.instance.pk:
            schemas = Schema.objects.from_instance(self.instance)
        elif schema_selectors is not None:
            selectors = []
            for ss in schema_selectors:
                selectors.append(ss['selector'])
                if ss['name'] is not None:
                    setattr(self.instance, ss['name'], ss['value'])
            content_type = ContentType.objects.get_for_model(self.Meta.model)
            schemas = Schema.objects.lookup(
                content_type=content_type, selectors=selectors
            )
            attrvals.setup_schema(schemas)
        attrs, _, _ = compose_schemas(*schemas)
        for name, attr in attrs.items():
            fieldname = self.attributes_field + '::' + name
            atype = attr.attr_type
            args = {'label': attr.long_name, 'required': False}
            field = form_field_from_name(atype.form_field)
            # if atype.form_field == 'CharField':
            #     args['max_length'] = 32
            if (atype.form_field == 'ChoiceField' or
               atype.form_field == 'MultipleChoiceField'):
                if attr.choice_labels is not None and attr.choice_labels != []:
                    chs = list(zip(attr.choices, attr.choice_labels))
                else:
                    chs = list(map(lambda c: (c, c), attr.choices))
                args['choices'] = chs
            if atype.form_field == 'BooleanField':
                args['required'] = False
                self.set_default(args, attr, boolean=True)
            elif attr.required:
                args['required'] = True
                self.set_default(args, attr)
            else:
                self.set_default(args, attr)
            self.set_initial(args, name, attr, attrvals)
            self.fields[fieldname] = field(**args)
项目:frisbeer-backend    作者:Moetto    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['players'] = forms.MultipleChoiceField(
            choices=[(player.id, player.name) for player in list(Player.objects.all())],
            validators=[validate_players],
            widget=forms.CheckboxSelectMultiple)
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        user = kwargs.pop('user',None)
        months = kwargs.pop('months',[])
        recentseries = kwargs.pop('recentseries',[])
        customers = kwargs.pop('customers',[])

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

        if customers:
            self.fields['customers'] = forms.MultipleChoiceField(
                required=True,
                label=_('Selected customers'),
                widget=forms.CheckboxSelectMultiple(),
                choices=[(x.id,'%s <%s>' % (x.fullName, x.email)) for x in customers]
            )
            self.fields['customers'].initial = [x.id for x in customers]
            self.fields.pop('month',None)
            self.fields.pop('series',None)
            self.fields.pop('sendToSet',None)

            # Move the customer list to the top of the form
            self.fields.move_to_end('customers',last=False)

        else:
            self.fields['month'].choices = months
            self.fields['series'].choices = recentseries

        if user:
            self.fields['template'].queryset = EmailTemplate.objects.filter(Q(groupRequired__isnull=True) | Q(groupRequired__in=user.groups.all())).filter(hideFromForm=False)
项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def __init__(self, users, *args, **kwargs):
        super(GroupAddForm, self).__init__(*args, **kwargs)
        self.fields['users'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                         choices=users)
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def prepare_form(self):
        res = init.get_sipinterface_default_ip_list()
        _choices= [(e,e) for e in res]
        class MyForm(forms.Form):
            ips = forms.MultipleChoiceField(label='??IP', choices=_choices)
        self.view_form = MyForm
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def PermField():
    #perms = ['read', 'add', 'update', 'delete', 'assign_group', 'remove_group']
    #return forms.MultipleChoiceField(choices=[(c,c) for c in perms])
    perms = ['read', 'write', 'admin', 'admin+delete']
    return forms.ChoiceField(choices=[(c,c) for c in perms])
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, event, *args, **kwargs):
        super(OptionsForm, self).__init__(*args, **kwargs)
        self.fields['conference_options'] = forms.MultipleChoiceField(
            choices=[(option.id, str(option)) for
                     option in EventOptions.objects.filter(event=event)],
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'form-control'}
            )
        )
项目:sasa    作者:lhmlihaomin    | 项目源码 | 文件源码
def map_field(self, cfield):
        label = cfield.title
        if cfield.required:
            suffix = "*"

        if cfield.field_type == "string":
            f = forms.CharField(required=cfield.required,
                                label=label,
                                label_suffix=suffix)
        elif cfield.field_type == "text":
            f = forms.CharField(required=cfield.required, 
                                widget=forms.Textarea, 
                                label=label,
                                label_suffix=suffix)
        elif cfield.field_type == "email":
            f = forms.EmailField(required=cfield.required, 
                                 label=label,
                                 label_suffix=suffix)
        elif cfield.field_type == "boolean":
            f = forms.BooleanField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "number":
            f = forms.FloatField(required=cfield.required, 
                                 label=label,
                                 label_suffix=suffix)
        elif cfield.field_type == "integer":
            f = forms.IntegerField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "select":
            f = forms.ChoiceField(required=cfield.required, 
                                  choices=cfield.choices, 
                                  label=label,
                                  label_suffix=suffix)
        elif cfield.field_type == "select_multiple":
            f = forms.MultipleChoiceField(required=cfield.required, 
                                          choices=cfield.choices, 
                                          label=label,
                                          label_suffix=suffix)
        elif cfield.field_type == "checkbox":
            f = forms.BooleanField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "radio":
            f = forms.ChoiceField(required=cfield.required, 
                                  choices=cfield.choices, 
                                  widget=forms.RadioSelect, 
                                  label=label,
                                  label_suffix=suffix)
        else:
            # return a generic text input:
            f = forms.CharField()
        return f