Python django.forms.MultipleChoiceField() Examples

The following are 30 code examples of django.forms.MultipleChoiceField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms , or try the search function .
Example #1
Source File: forms.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 7 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 #2
Source File: forms.py    From SEMS with 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 #3
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_1(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '2'], f.clean(['1', '2']))
        self.assertEqual(['1', '2'], f.clean([1, '2']))
        self.assertEqual(['1', '2'], f.clean((1, '2')))
        with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean([])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(())
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['3']) 
Example #4
Source File: forms.py    From registrasion with 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 #5
Source File: fields.py    From django-ca with 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 #6
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_2(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
        self.assertEqual([], f.clean(''))
        self.assertEqual([], f.clean(None))
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '2'], f.clean(['1', '2']))
        self.assertEqual(['1', '2'], f.clean([1, '2']))
        self.assertEqual(['1', '2'], f.clean((1, '2')))
        with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        self.assertEqual([], f.clean([]))
        self.assertEqual([], f.clean(()))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['3']) 
Example #7
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_3(self):
        f = MultipleChoiceField(
            choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]
        )
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '5'], f.clean([1, 5]))
        self.assertEqual(['1', '5'], f.clean([1, '5']))
        self.assertEqual(['1', '5'], f.clean(['1', 5]))
        self.assertEqual(['1', '5'], f.clean(['1', '5']))
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['6'])
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['1', '6']) 
Example #8
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_1(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '2'], f.clean(['1', '2']))
        self.assertEqual(['1', '2'], f.clean([1, '2']))
        self.assertEqual(['1', '2'], f.clean((1, '2')))
        with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean([])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(())
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['3']) 
Example #9
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_2(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
        self.assertEqual([], f.clean(''))
        self.assertEqual([], f.clean(None))
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '2'], f.clean(['1', '2']))
        self.assertEqual(['1', '2'], f.clean([1, '2']))
        self.assertEqual(['1', '2'], f.clean((1, '2')))
        with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        self.assertEqual([], f.clean([]))
        self.assertEqual([], f.clean(()))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['3']) 
Example #10
Source File: forms.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 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 #11
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiplechoicefield_3(self):
        f = MultipleChoiceField(
            choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]
        )
        self.assertEqual(['1'], f.clean([1]))
        self.assertEqual(['1'], f.clean(['1']))
        self.assertEqual(['1', '5'], f.clean([1, 5]))
        self.assertEqual(['1', '5'], f.clean([1, '5']))
        self.assertEqual(['1', '5'], f.clean(['1', 5]))
        self.assertEqual(['1', '5'], f.clean(['1', '5']))
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['6'])
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(['1', '6']) 
Example #12
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #13
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disabled_has_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], disabled=True)
        self.assertIs(f.has_changed('x', 'y'), False) 
Example #14
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiplechoicefield_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
        self.assertFalse(f.has_changed(None, None))
        self.assertFalse(f.has_changed([], None))
        self.assertTrue(f.has_changed(None, ['1']))
        self.assertFalse(f.has_changed([1, 2], ['1', '2']))
        self.assertFalse(f.has_changed([2, 1], ['1', '2']))
        self.assertTrue(f.has_changed([1, 2], ['1']))
        self.assertTrue(f.has_changed([1, 2], ['1', '3'])) 
Example #15
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiplechoicefield_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
        self.assertFalse(f.has_changed(None, None))
        self.assertFalse(f.has_changed([], None))
        self.assertTrue(f.has_changed(None, ['1']))
        self.assertFalse(f.has_changed([1, 2], ['1', '2']))
        self.assertFalse(f.has_changed([2, 1], ['1', '2']))
        self.assertTrue(f.has_changed([1, 2], ['1']))
        self.assertTrue(f.has_changed([1, 2], ['1', '3'])) 
Example #16
Source File: test_multiplechoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disabled_has_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], disabled=True)
        self.assertIs(f.has_changed('x', 'y'), False) 
Example #17
Source File: forms.py    From anytask with MIT License 5 votes vote down vote up
def get_followers_form(field_name, request, issue, data=None, *args, **kwargs):
    class _form(DefaultForm):
        followers_names = forms.MultipleChoiceField(get_users_choise(issue, 'followers'), required=False,
                                                    label='')  # we dont need coerce function here
        # because add user id to m2m field is ok.

    return _form(field_name, request, issue, data, *args, **kwargs) 
Example #18
Source File: forms.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prepare_checkbox_multiple(self, field):
        field_attrs = field.build_field_attrs()
        widget_attrs = field.build_widget_attrs()

        field_attrs.update({
            'widget': forms.CheckboxSelectMultiple(attrs=widget_attrs),
            'choices': field.get_choices(),
        })

        if field.initial:
            field_attrs.update({
                'initial': self.split_choices(field.initial)
            })
        return forms.MultipleChoiceField(**field_attrs) 
Example #19
Source File: forms.py    From jeeves with MIT License 5 votes vote down vote up
def __init__(self, possible_reviewers, default_conflict_reviewers, *args, **kwargs):
        super(SubmitForm, self).__init__(*args, **kwargs)

        choices = []
        for r in possible_reviewers:
            choices.append((r.username, r))

        self.fields['conflicts'] = MultipleChoiceField(widget=CheckboxSelectMultiple(), required=False, choices=choices, initial=list(default_conflict_reviewers)) 
Example #20
Source File: forms.py    From jeeves with MIT License 5 votes vote down vote up
def __init__(self, possible_reviewers, default_conflict_reviewers, *args, **kwargs):
        super(SubmitForm, self).__init__(*args, **kwargs)

        choices = []
        for r in possible_reviewers:
            choices.append((r.username, r))

        self.fields['conflicts'] = MultipleChoiceField(widget=CheckboxSelectMultiple(), required=False, choices=choices, initial=list(default_conflict_reviewers)) 
Example #21
Source File: forms.py    From jeeves with MIT License 5 votes vote down vote up
def __init__(self, possible_reviewers, default_conflict_reviewers, *args, **kwargs):
        super(SubmitForm, self).__init__(*args, **kwargs)

        choices = []
        for r in possible_reviewers:
            choices.append((r.username, r))

        self.fields['conflicts'] = MultipleChoiceField(widget=CheckboxSelectMultiple(), required=False, choices=choices, initial=list(default_conflict_reviewers)) 
Example #22
Source File: forms.py    From jeeves with MIT License 5 votes vote down vote up
def __init__(self, possible_reviewers, default_conflict_reviewers, *args, **kwargs):
        super(SubmitForm, self).__init__(*args, **kwargs)

        choices = []
        for r in possible_reviewers:
            choices.append((r.username, r))

        self.fields['conflicts'] = MultipleChoiceField(widget=CheckboxSelectMultiple(), required=False, choices=choices, initial=list(default_conflict_reviewers)) 
Example #23
Source File: test_blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multi_select_enabled(self):
        field = self.get_field(multi=True)
        self.assertTrue(isinstance(field, forms.MultipleChoiceField)) 
Example #24
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field_class(self, struct_value):
        if struct_value['multi']:
            return forms.MultipleChoiceField
        else:
            return forms.ChoiceField 
Example #25
Source File: fields.py    From Dailyfresh-B2C with 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 #26
Source File: base.py    From richie with 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 #27
Source File: test_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_checkboxes_field(self):
        data = self.get_form_field_data("checkboxes")
        cls = wsf_fields.CheckboxesField()
        field = cls.get_formfield(data)

        self.assertIsInstance(field, forms.MultipleChoiceField)
        self.assertIsInstance(field.widget, forms.widgets.CheckboxSelectMultiple)
        self.assertEqual(field.label, data["label"])
        self.assertEqual(field.required, data["required"])
        self.assertEqual(field.help_text, data["help_text"])
        self.assertEqual(field.choices, [(c, c) for c in data["choices"]]) 
Example #28
Source File: forms.py    From Spirit with MIT License 5 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 #29
Source File: field_block.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field(self, **kwargs):
        return forms.MultipleChoiceField(**kwargs) 
Example #30
Source File: forms.py    From lexpredict-contraxsuite with 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'])