Python django.forms.MultipleChoiceField() Examples

The following are code examples for showing how to use django.forms.MultipleChoiceField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: scope   Author: CCA-Public   File: forms.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        # Get and add initial groups (must be done before super init)
        self.initial_groups = []
        if "instance" in kwargs:
            self.initial_groups = list(
                kwargs["instance"].groups.values_list("id", flat=True)
            )
            kwargs["initial"] = {"groups": self.initial_groups}
        super().__init__(*args, **kwargs)
        # Add group fields (must be done after super init)
        self.fields["groups"] = forms.MultipleChoiceField(
            choices=Group.objects.all().values_list("id", "name"),
            required=False,
            label=_("Groups"),
            help_text=_("Ctrl + Click to select multiple or unselect."),
        )
        # Do not require password fields when editing
        if "instance" in kwargs:
            self.fields["password1"].required = False
            self.fields["password2"].required = False 
Example 2
Project: recharge-me   Author: campus-connect   File: forms.py    MIT License 6 votes vote down vote up
def __init__(self, poll, user=None, *args, **kwargs):
        super(PollVoteManyForm, self).__init__(*args, **kwargs)
        self.auto_id = 'id_poll_{pk}_%s'.format(pk=poll.pk)  # Uniqueness "<label for=id_poll_pk_..."
        self.user = user
        self.poll = poll
        self.poll_choices = getattr(poll, 'choices', poll.poll_choices.unremoved())
        choices = ((c.pk, mark_safe(c.description)) for c in self.poll_choices)

        if poll.is_multiple_choice:
            self.fields['choices'] = forms.MultipleChoiceField(
                choices=choices,
                widget=forms.CheckboxSelectMultiple,
                label=_("Poll choices")
            )
        else:
            self.fields['choices'] = forms.ChoiceField(
                choices=choices,
                widget=forms.RadioSelect,
                label=_("Poll choices")
            ) 
Example 3
Project: SEMS   Author: urankajtazaj   File: forms.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['emri'].widget.attrs.update({'class': 'form-control'})

            

# class LendetForm(forms.ModelForm):

#     class Meta:
#         model = ProvimetMundshme
#         fields = '__all__'

#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.fields['program'].widget.attrs.update({'class': 'form-control', 'data-type': 'program-listener'})
#         self.fields['semester'].widget.attrs.update({'class': 'form-control'})
#         self.fields['year'].widget.attrs.update({'class': 'form-control'})
#         self.fields['level'].widget.attrs.update({'class': 'form-control'})

#     course = forms.MultipleChoiceField(
#         widget=forms.CheckboxSelectMultiple,
#         choices=[(c.pk, c.name) for c in Course.objects.all()],
#     ) 
Example 4
Project: acceptable   Author: canonical-ols   File: test_djangoutils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_get_field_schema_multiple_choice_checkbox_widget(self):
        field = forms.MultipleChoiceField(
            label='label',
            help_text='help',
            choices=['A', 'B', 'C'],
            widget=forms.CheckboxSelectMultiple(),
        )
        self.assertEqual(
            {
                'type': 'array',
                'title': 'label',
                'description': 'help',
                'items': {
                    'type': 'string',
                    'enum': ['A', 'B', 'C'],
                }
            },
            djangoutil.get_field_schema('name', field),
        ) 
Example 5
Project: AgendaTCC   Author: agendaTCC   File: forms.py    GNU General Public License v2.0 6 votes vote down vote up
def correctField(self,label, opcoes,tipo = 0, initial = None):
		if tipo =='0':
			return forms.CharField(label=label,required=False,  widget=forms.Textarea, initial = initial)
		elif tipo =='1':
			return forms.ChoiceField(label = label,required=False, choices = ((u'sim',u'sim'),(u'não',u'não')), widget= forms.RadioSelect, initial = initial)
		elif tipo=='2':
			if opcoes:
				return forms.ChoiceField(label = label,required=False, choices = self.cleanOptions(opcoes), widget= forms.RadioSelect, initial = initial)
			else:
				return forms.CharField(label=label,required=False, widget=forms.Textarea, initial = initial)
		elif tipo=='3':
			if opcoes:
				return forms.MultipleChoiceField(label=label,required=False, widget=forms.CheckboxSelectMultiple, choices=self.cleanOptions(opcoes), initial = initial)
			else:
				return forms.CharField(label=label,required=False, widget=forms.Textarea, initial = initial)
		elif tipo=='4':	
			return forms.CharField(label='<h3>'+label+'</h3>',required=False, widget=forms.TextInput(attrs={'readonly':'readonly'}))
		else:
			return forms.CharField(label=label,required=False, widget=forms.Textarea) 
Example 6
Project: django-ca   Author: mathiasertl   File: fields.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, extension, *args, **kwargs):
        self.extension = extension
        kwargs.setdefault('label', extension.name)
        ext = profile.extensions.get(self.extension.key)
        if ext:
            ext = ext.serialize()
            kwargs.setdefault('initial', [ext['value'], ext['critical']])

        fields = (
            forms.MultipleChoiceField(required=False, choices=extension.CHOICES),
            forms.BooleanField(required=False),
        )

        widget = MultiValueExtensionWidget(choices=extension.CHOICES)
        super(MultiValueExtensionField, self).__init__(
            fields=fields, require_all_fields=False, widget=widget,
            *args, **kwargs) 
Example 7
Project: registrasion   Author: chrisjrn   File: forms.py    Apache License 2.0 6 votes vote down vote up
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 
Example 8
Project: i-portalen   Author: I-sektionen   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SegmentUsersForm, self).__init__(*args, **kwargs)
        self.fields['bachelor_profile'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                                    required=False,
                                                                    choices=[(o.pk, o.name) for o in BachelorProfile.objects.all()])

        self.fields['master_profile'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                                  required=False,
                                                                  choices=[(o.pk, o.name) for o in MasterProfile.objects.all()]) 
Example 9
Project: wagtailplus   Author: MechanisM   File: mailchimp_page.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def mailchimp_grouping_factory(self, grouping):
        """
        Returns form field instance for specified MailChimp grouping.

        :param grouping: grouping dictionary.
        :rtype: django.forms.Field.
        """
        field_type  = grouping.get('form_field', None)
        name        = grouping.get('name', None)
        groups      = grouping.get('groups', [])
        choices     = ((x['name'], x['name']) for x in groups)
        kwargs      = {'label': name, 'choices': choices, 'required': False}

        if field_type == 'checkboxes':
            kwargs.update({'widget': forms.CheckboxSelectMultiple})
            return forms.MultipleChoiceField(**kwargs)

        if field_type == 'radio':
            kwargs.update({'widget': forms.RadioSelect})
            return forms.ChoiceField(**kwargs)

        if field_type == 'dropdown':
            kwargs.update({'widget': forms.Select})
            return forms.ChoiceField(**kwargs)

        if field_type == 'hidden':
            kwargs.update({'widget': forms.HiddenInput})
            return forms.ChoiceField(**kwargs) 
Example 10
Project: django-guardian   Author: zulip   File: forms.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_obj_perms_field_class(self):
        """
        Returns object permissions management field's base class. Default:
        ``django.forms.MultipleChoiceField``.
        """
        return forms.MultipleChoiceField 
Example 11
Project: cosinnus-core   Author: wechange-eg   File: select2.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        """
        Value is stored and retrieved as a string of comma separated
        integers. We don't want to do processing to convert the value to
        a list like the normal MultipleChoiceField does.
        """
        return value 
Example 12
Project: cosinnus-core   Author: wechange-eg   File: select2.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, value):
        """
        If we have a value, then we know it is a string of comma separated
        integers. To use the MultipleChoiceField validator, we first have
        to convert the value to a list.
        """
        if value:
            value = value.split(',')
        super(CommaSeparatedSelect2MultipleChoiceField, self).validate(value) 
Example 13
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {
            'form_class': forms.MultipleChoiceField,
            'choices': self.base_field.choices,
        }
        defaults.update(kwargs)
        # Skip our parent's formfield implementation completely as we don't
        # care for it.
        # pylint:disable=bad-super-call
        return super(ArrayField, self).formfield(**defaults) 
Example 14
Project: saleor-demo   Author: vubon   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def filters(context, filter_set, sort_by_filter_name='sort_by'):
    """Render the filtering template based on the filter set."""
    chips = []
    request_get = context['request'].GET.copy()
    for filter_name in filter_set.form.cleaned_data.keys():
        if filter_name == sort_by_filter_name:
            # Skip processing of sort_by filter, as it's rendered differently
            continue

        field = filter_set.form[filter_name]
        if field.value() not in ['', None]:
            if isinstance(field.field, forms.NullBooleanField):
                items = handle_nullboolean(field, request_get)
            elif isinstance(field.field, forms.ModelMultipleChoiceField):
                items = handle_multiple_model_choice(field, request_get)
            elif isinstance(field.field, forms.MultipleChoiceField):
                items = handle_multiple_choice(field, request_get)
            elif isinstance(field.field, forms.ModelChoiceField):
                items = handle_single_model_choice(field, request_get)
            elif isinstance(field.field, forms.ChoiceField):
                items = handle_single_choice(field, request_get)
            elif isinstance(field.field, RangeField):
                items = handle_range(field, request_get)
            else:
                items = handle_default(field, request_get)
            chips.extend(items)
    return {
        'chips': chips, 'filter': filter_set,
        'sort_by': request_get.get(sort_by_filter_name, None)} 
Example 15
Project: openode   Author: JvGinkel   File: values.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def choice_field(self, **kwargs):
        kwargs['required'] = False
        return forms.MultipleChoiceField(choices=self.choices, **kwargs) 
Example 16
Project: agir.lafranceinsoumise.fr   Author: lafranceinsoumise   File: model_fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {
            "form_class": forms.MultipleChoiceField,
            "choices": self.base_field.choices,
        }
        defaults.update(kwargs)

        return super(ArrayField, self).formfield(**defaults) 
Example 17
Project: django_material_widgets   Author: ooknosi   File: test_forms.py    Apache License 2.0 5 votes vote down vote up
def test_MaterialForm_materializes_CheckboxSelectMultiple(self):
        """django.forms.widgets.CheckboxSelectMultiple should be converted to
        material_widgets.widgets.MaterialCheckboxSelectMultiple.
        """

        class MultipleChoiceForm(MaterialForm):
            checkbox_select_multiple = forms.MultipleChoiceField(
                widget=forms.widgets.CheckboxSelectMultiple(),
                )

        form = MultipleChoiceForm()
        self.assertEqual(
            type(form.fields['checkbox_select_multiple'].widget),
            widgets.MaterialCheckboxSelectMultiple,
            ) 
Example 18
Project: django_material_widgets   Author: ooknosi   File: test_forms.py    Apache License 2.0 5 votes vote down vote up
def test_MaterialForm_materializes_MultipleChoiceField(self):
        """django.forms.widgets.SelectMultiple should be converted to
        material_widgets.widgets.MaterialSelectMultiple.
        """

        class SelectMultipleForm(MaterialForm):
            select_multiple = forms.MultipleChoiceField()

        form = SelectMultipleForm()
        self.assertEqual(
            type(form.fields['select_multiple'].widget),
            widgets.MaterialSelectMultiple,
            ) 
Example 19
Project: django_material_widgets   Author: ooknosi   File: test_forms.py    Apache License 2.0 5 votes vote down vote up
def test_MaterialForm_materializes_MultipleHiddenInput(self):
        """django.forms.widgets.MultipleHiddenInput should be converted to
        material_widgets.widgets.MaterialMultipleHiddenInput.
        """

        class MultipleHiddenInputForm(MaterialForm):
            multiple_hidden_input = forms.MultipleChoiceField(
                widget=forms.widgets.MultipleHiddenInput(),
                )

        form = MultipleHiddenInputForm()
        self.assertEqual(
            type(form.fields['multiple_hidden_input'].widget),
            widgets.MaterialMultipleHiddenInput,
            ) 
Example 20
Project: driving-reserve   Author: liukaijv   File: test_filters.py    MIT License 5 votes vote down vote up
def test_default_field(self):
        f = MultipleChoiceFilter()
        field = f.field
        self.assertIsInstance(field, forms.MultipleChoiceField) 
Example 21
Project: acceptable   Author: canonical-ols   File: test_djangoutils.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_get_field_schema_multiple_choice(self):
        field = forms.MultipleChoiceField(
            label='label', help_text='help', choices=['A', 'B', 'C'])
        self.assertEqual(
            {
                'type': 'array',
                'title': 'label',
                'description': 'help',
                'items': {
                    'type': 'string',
                    'enum': ['A', 'B', 'C'],
                }
            },
            djangoutil.get_field_schema('name', field),
        ) 
Example 22
Project: AgendaTCC   Author: agendaTCC   File: forms.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ModelSearchForm, self).__init__(*args, **kwargs)
        self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label=_('Buscar em'), widget=forms.CheckboxSelectMultiple) 
Example 23
Project: janeway   Author: BirkbeckCTP   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        settings = kwargs.pop('settings', None)
        super(GeneratedPluginSettingForm, self).__init__(*args, **kwargs)

        for field in settings:

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

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

        for field in settings:

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

            self.fields[field['name']].label = object.setting.pretty_name
            self.fields[field['name']].initial = object.processed_value
            self.fields[field['name']].help_text = object.setting.description 
Example 25
Project: lexpredict-contraxsuite   Author: LexPredict   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['task_queue'] = forms.MultipleChoiceField(
            choices=[(tq.pk, tq.__str__()) for tq in TaskQueue.objects.all()],
            required=True) 
Example 26
Project: lexpredict-contraxsuite   Author: LexPredict   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['project'] = forms.MultipleChoiceField(
            choices=[(p.pk, p.__str__()) for p in Project.objects.all()],
            required=True) 
Example 27
Project: lexpredict-contraxsuite   Author: LexPredict   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['document_type'] = forms.MultipleChoiceField(
            choices=[(t, t) for t in Document.objects
                .order_by().values_list('document_type', flat=True).distinct()],
            widget=forms.SelectMultiple(attrs={'class': 'chosen'}),
            required=False)
        self.fields = OrderedDict((k, self.fields[k]) for k in ['document_type', 'no_detect', 'delete']) 
Example 28
Project: lexpredict-contraxsuite   Author: LexPredict   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['document_type'] = forms.MultipleChoiceField(
            choices=[(t, t) for t in Document.objects
                .order_by().values_list('document_type', flat=True).distinct()],
            widget=forms.SelectMultiple(attrs={'class': 'chosen'}),
            required=False)
        self.fields = OrderedDict((k, self.fields[k])
                                  for k in ['document_type', 'no_detect', 'delete']) 
Example 29
Project: richie   Author: openfun   File: base.py    MIT License 5 votes vote down vote up
def get_form_fields(self):
        """Choice filters are validated with a MultipleChoiceField."""
        return {
            self.name: (
                forms.MultipleChoiceField(
                    required=False, choices=self.get_values().items()
                ),
                True,  # a MultipleChoiceField expects list values
            )
        } 
Example 30
Project: ciaas   Author: ppc64le   File: models.py    Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text,
                    'choices': self.choices}
        defaults.update(kwargs)
        return forms.MultipleChoiceField(**defaults) 
Example 31
Project: airavata-django-portal   Author: apache   File: forms.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, data=None, user_choices=None):
        super().__init__(data=data)
        self.fields["users"] = forms.MultipleChoiceField(
            widget=forms.CheckboxSelectMultiple, choices=user_choices) 
Example 32
Project: airavata-django-portal   Author: apache   File: forms.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, data=None, user_choices=None):
        super().__init__(data=data)
        self.fields["members"] = forms.MultipleChoiceField(
            widget=forms.CheckboxSelectMultiple, choices=user_choices) 
Example 33
Project: dbms-project-parliament-elections   Author: ayshrv   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.list_refined=[]
        self.list_with_index=[]
        list = kwargs.pop('list')
        for i in list:
            self.list_refined.append(i[0])
        for index, value in enumerate(self.list_refined):
            self.list_with_index.append((index,str(value)))
        super(VerifyCandiForm, self).__init__(*args, **kwargs)
        self.fields['Candidates'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.list_with_index,required=False) 
Example 34
Project: dbms-project-parliament-elections   Author: ayshrv   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.list_refined=[]
        self.list_with_index=[]
        list = kwargs.pop('list')
        for i in list:
            print(i)
            self.list_refined.append(i)
        for index, value in enumerate(self.list_refined):
            self.list_with_index.append((index,str(value)))
        super(VotingForm, self).__init__(*args, **kwargs)
        self.fields['Candidates'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.list_with_index,required=False) 
Example 35
Project: dbms-project-parliament-elections   Author: ayshrv   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.list_with_index=[]
        self.list1=[]
        list = kwargs.pop('list')
        for i in list:
            self.list1.append(i)
        for index, value in enumerate(self.list1):
            self.list_with_index.append((index,str(value)))
        super(ChoiceResultForm, self).__init__(*args, **kwargs)
        # self.fields['Candidates'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.list_with_index,required=False)
        self.fields['ResultID'] = forms.ChoiceField(choices=self.list_with_index,required=True) 
Example 36
Project: e-colle   Author: stephanekirsch   File: forms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,classe,*args,**kwargs):
        super().__init__(*args,**kwargs)
        query = iter(Eleve.objects.filter(classe=classe).annotate(groupe_nom=Coalesce('groupe__nom',Value(100))).select_related('user').order_by('groupe_nom','user__last_name','user__first_name'))
        listeGroupes = Groupe.objects.filter(classe=classe).annotate(nb=Count('groupeeleve')).order_by('nom')
        choices_groupe = [(groupe.pk, "Groupe {}".format(groupe.nom)) for groupe in listeGroupes]
        choices = [(0,"Élève fictif")]
        indexFictif = -1
        for x in listeGroupes:
            for i in range(x.nb):
                eleve = next(query)
                choices.append((eleve.pk,str(eleve)))
            for j in range(3-x.nb):
                choices.append((indexFictif,"Élève fictif"))
                indexFictif -= 1
        modulo = 0
        while True:
            try:
                eleve = next(query)
                choices.append((eleve.pk,str(eleve)))
                modulo += 1
            except Exception:
                break
        for j in range(3 - (modulo % 3)):
            choices.append((indexFictif,"Élève fictif"))
            indexFictif -= 1
        self.tailleGroupes = [x.nb for x in listeGroupes]
        self.fields['groupe'] = forms.MultipleChoiceField(choices=choices_groupe, widget = forms.CheckboxSelectMultiple, required = False)
        self.fields['eleve'] = forms.MultipleChoiceField(choices=choices, widget = forms.CheckboxSelectMultiple, required = True) 
Example 37
Project: cartridge   Author: andyzsf   File: forms.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __new__(cls, name, bases, attrs):
        for option in settings.SHOP_OPTION_TYPE_CHOICES:
            field = forms.MultipleChoiceField(label=option[1],
                required=False, widget=forms.CheckboxSelectMultiple)
            attrs["option%s" % option[0]] = field
        args = (cls, name, bases, attrs)
        return super(ProductAdminFormMetaclass, cls).__new__(*args) 
Example 38
Project: notabanane   Author: ellmetha   File: fields.py    GNU General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        """ Returns the form field associated with the field. """
        defaults = {'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices}
        defaults.update(kwargs)
        return super(ArrayField, self).formfield(**defaults) 
Example 39
Project: notabanane   Author: ellmetha   File: test_fields.py    GNU General Public License v3.0 5 votes vote down vote up
def test_formfield_returns_a_multiple_choice_form_field(self):
        TestField = namedtuple('TestField', ['choices'])
        field = TestField(choices=[('', 'Default'), ('c1', 'Choice 1')])
        formfield = ChoiceArrayField(field).formfield()
        assert isinstance(formfield, forms.MultipleChoiceField)
        assert formfield.choices == [('', 'Default'), ('c1', 'Choice 1')] 
Example 40
Project: bockus   Author: phildini   File: book_views.py    MIT License 5 votes vote down vote up
def get_form(self, form_class=None):
        form = forms.Form(**self.get_form_kwargs())
        queryset = self.get_queryset()
        page_size = self.get_paginate_by(queryset)
        page_num = 1
        if self.request.GET.get('page'):
            page_num = int(self.request.GET.get('page'))
        else:
            page_num = int(form.data.get('page', 1))
        paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
        choices = [
            (
                book.id, 
                {
                    'book':book,
                    'last_emailed': book.last_emailed(self.request.user),
                }
            ) for book in paginator.page(page_num)
        ]
        actions = [
            ('shelve', 'Add to shelf...'),
            ('merge', 'Merge Selected'),
            ('delete', 'Delete Selected'),
        ]
        form.fields['books'] = forms.MultipleChoiceField(
            required=False,
            choices=choices,
            widget=forms.CheckboxSelectMultiple()
        )
        form.fields['actions'] = forms.ChoiceField(
            required=False,
            choices=actions,
        )
        form.fields['page'] = forms.IntegerField(
            required=False,
            widget=forms.HiddenInput()
        )
        return form 
Example 41
Project: bockus   Author: phildini   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        token = kwargs.pop('token')
        client = kwargs.pop('client')
        super(ImportForm, self).__init__(*args, **kwargs)
        choices = [('select_all_option', 'Select All')]
        metadata = client.metadata('/')
        directories = [(item.get('path'), item.get('path')) for item in metadata.get('contents') if item.get('is_dir')]
        choices += directories

        self.fields['folders'] = forms.MultipleChoiceField(
            required=True,
            choices=choices,
            widget=forms.CheckboxSelectMultiple(),
        ) 
Example 42
Project: joeflow   Author: codingjoe   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_form_class(self):
        form_class = super().get_form_class()

        class OverrideForm(form_class):
            next_tasks = forms.MultipleChoiceField(
                label=t('Next tasks'),
                choices=self.get_task_choices(self.object),
            )

        return OverrideForm 
Example 43
Project: Dailyfresh-B2C   Author: BeanWei   File: fields.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.empty_label = None
        super(MultipleChoiceField, self).__init__(*args, **kwargs) 
Example 44
Project: cadasta-platform   Author: Cadasta   File: form_mixins.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def create_model_fields(self, field_prefix, attribute_map, new_item=False):
        for selector, attributes in attribute_map.items():
            for name, attr in attributes.items():
                fieldname = '{}::{}::{}'.format(
                    field_prefix, selector.lower(), name)
                atype = attr.attr_type

                field_kwargs = {
                    'label': attr.long_name, 'required': attr.required
                }
                field = form_field_from_name(atype.form_field)
                if not new_item:
                    self.set_initial(field_kwargs, attr.name, attr)
                if atype.form_field in ['ChoiceField', 'MultipleChoiceField']:
                    if (attr.choice_labels is not None and
                            attr.choice_labels != []):
                        chs = list(zip(attr.choices, attr.choice_labels))
                    else:
                        chs = [(c, c) for c in attr.choices]

                    field_kwargs['choices'] = [('', '')] + chs
                if atype.form_field == 'BooleanField':
                    field_kwargs['required'] = attr.required
                    if len(attr.default) > 0:
                        self.set_default(field_kwargs, attr, boolean=True)
                else:
                    if attr.required and new_item:
                        field_kwargs['required'] = True
                    if len(attr.default) > 0 and len(str(
                            field_kwargs.get('initial', ''))) == 0:
                        self.set_default(field_kwargs, attr)

                f = field(**field_kwargs)

                if hasattr(f.widget, 'choices'):
                    try:
                        xlang_labels = dict(zip(attr.choices,
                                                attr.choice_labels_xlat))
                    except TypeError:
                        xlang_labels = {}

                    widget_args = {
                        'attrs': f.widget.attrs,
                        'choices': f.widget.choices,
                        'xlang_labels': xlang_labels
                    }

                    if isinstance(f, MultipleChoiceField):
                        f.widget = XLangSelectMultiple(**widget_args)
                    else:
                        f.widget = XLangSelect(**widget_args)

                f.labels_xlang = template_xlang_labels(attr.long_name_xlat)
                self.fields[fieldname] = f 
Example 45
Project: django-jsonattrs   Author: Cadasta   File: forms.py    GNU Affero General Public License v3.0 4 votes vote down vote up
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) 
Example 46
Project: dbms-project-parliament-elections   Author: ayshrv   File: forms.py    MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.first_list_refined=[]
        self.first_list_with_index=[]
        self.second_list_refined=[]
        self.second_list_with_index=[]
        self.third_list_refined=[]
        self.third_list_with_index=[]
        self.fourth_list_refined=[]
        self.fourth_list_with_index=[]
        self.phd_list_refined=[]
        self.phd_list_with_index=[]
        self.first = kwargs.pop('first')
        self.first_left = kwargs.pop('first_left')
        self.second = kwargs.pop('second')
        self.second_left = kwargs.pop('second_left')
        self.third = kwargs.pop('third')
        self.third_left = kwargs.pop('third_left')
        self.fourth = kwargs.pop('fourth')
        self.fourth_left = kwargs.pop('fourth_left')
        self.phd = kwargs.pop('phd')
        self.phd_left = kwargs.pop('phd_left')
        for i in self.first:
            self.first_list_refined.append(i)
        for index, value in enumerate(self.first_list_refined):
            self.first_list_with_index.append((index,str(value)))

        for i in self.second:
            self.second_list_refined.append(i)
        for index, value in enumerate(self.second_list_refined):
            self.second_list_with_index.append((index,str(value)))

        for i in self.third:
            self.third_list_refined.append(i)
        for index, value in enumerate(self.third_list_refined):
            self.third_list_with_index.append((index,str(value)))

        for i in self.fourth:
            self.fourth_list_refined.append(i)
        for index, value in enumerate(self.fourth_list_refined):
            self.fourth_list_with_index.append((index,str(value)))

        for i in self.phd:
            self.phd_list_refined.append(i)
        for index, value in enumerate(self.phd_list_refined):
            self.phd_list_with_index.append((index,str(value)))

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

        self.fields['First Year'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.first_list_with_index,required=False)
        self.fields['Second Year'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.second_list_with_index,required=False)
        self.fields['Third Year'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.third_list_with_index,required=False)
        self.fields['Fourth Year'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.fourth_list_with_index,required=False)
        self.fields['Ph.D'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.phd_list_with_index,required=False)