django.forms.MultipleChoiceField - python examples

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

25 Examples 7

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : codingjoe
    def get_form_clast(self):
        form_clast = super().get_form_clast()

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

        return OverrideForm

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def __init__(self, *args, **kwargs):
        super(EditUserForm, self).__init__(*args, **kwargs)
        self.fields["pastword1"].required = False
        self.fields["pastword1"].help_text = u"Keep this field blank if you don't want to change the pastword"
        self.fields["pastword2"].required = False
        self.fields["pastword2"].help_text = u"Keep this field blank if you don't want to change the pastword"
        current_request = CrequestMiddleware.get_request()
        boards = get_user_boards(current_request.user).filter(is_archived=False).order_by("name")
        self.fields["boards"] = forms.MultipleChoiceField(
            label=u"Boards",
            choices=[(board.id, board.name) for board in boards],
            initial=[board.id for board in self.instance.boards.all().order_by("name")],
            help_text=u"Boards this visitor will have access",
            required=False,
        )
        self.fields["boards"].widget.attrs={'size': boards.count()}

3 View Complete Implementation : entry.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def formfield(self, **kwargs):
        defaults = {
            'form_clast': forms.MultipleChoiceField,
            'choices': self.base_field.choices,
        }
        defaults.update(kwargs)
        return super(ArrayField, self).formfield(**defaults)

3 View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
    def test_multiselect_field(self):
        data = self.get_form_field_data('multiselect')
        cls = wsf_fields.MultiSelectField()
        field = cls.get_formfield(data)

        self.astertIsInstance(field, forms.MultipleChoiceField)
        self.astertIsInstance(field.widget, forms.widgets.SelectMultiple)
        self.astertEqual(field.label, data['label'])
        self.astertEqual(field.required, data['required'])
        self.astertEqual(field.help_text, data['help_text'])
        self.astertEqual(field.choices, [(c, c) for c in data['choices']])

3 View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
    def test_checkboxes_field(self):
        data = self.get_form_field_data('checkboxes')
        cls = wsf_fields.CheckboxesField()
        field = cls.get_formfield(data)

        self.astertIsInstance(field, forms.MultipleChoiceField)
        self.astertIsInstance(field.widget, forms.widgets.CheckboxSelectMultiple)
        self.astertEqual(field.label, data['label'])
        self.astertEqual(field.required, data['required'])
        self.astertEqual(field.help_text, data['help_text'])
        self.astertEqual(field.choices, [(c, c) for c in data['choices']])

3 View Complete Implementation : test_multiplechoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiplechoicefield_2(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
        self.astertEqual([], f.clean(''))
        self.astertEqual([], f.clean(None))
        self.astertEqual(['1'], f.clean([1]))
        self.astertEqual(['1'], f.clean(['1']))
        self.astertEqual(['1', '2'], f.clean(['1', '2']))
        self.astertEqual(['1', '2'], f.clean([1, '2']))
        self.astertEqual(['1', '2'], f.clean((1, '2')))
        with self.astertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        self.astertEqual([], f.clean([]))
        self.astertEqual([], f.clean(()))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean(['3'])

3 View Complete Implementation : test_multiplechoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiplechoicefield_3(self):
        f = MultipleChoiceField(
            choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]
        )
        self.astertEqual(['1'], f.clean([1]))
        self.astertEqual(['1'], f.clean(['1']))
        self.astertEqual(['1', '5'], f.clean([1, 5]))
        self.astertEqual(['1', '5'], f.clean([1, '5']))
        self.astertEqual(['1', '5'], f.clean(['1', 5]))
        self.astertEqual(['1', '5'], f.clean(['1', '5']))
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean(['6'])
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean(['1', '6'])

3 View Complete Implementation : test_multiplechoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiplechoicefield_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
        self.astertFalse(f.has_changed(None, None))
        self.astertFalse(f.has_changed([], None))
        self.astertTrue(f.has_changed(None, ['1']))
        self.astertFalse(f.has_changed([1, 2], ['1', '2']))
        self.astertFalse(f.has_changed([2, 1], ['1', '2']))
        self.astertTrue(f.has_changed([1, 2], ['1']))
        self.astertTrue(f.has_changed([1, 2], ['1', '3']))

3 View Complete Implementation : test_multivaluefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def __init__(self, **kwargs):
        fields = (
            CharField(),
            MultipleChoiceField(choices=beatles),
            SplitDateTimeField(),
        )
        super().__init__(fields, **kwargs)

3 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiplechoicefield(self):
        e = {
            'required': 'REQUIRED',
            'invalid_choice': '%(value)s IS INVALID CHOICE',
            'invalid_list': 'NOT A LIST',
        }
        f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['NOT A LIST'], f.clean, 'b')
        self.astertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b'])

3 View Complete Implementation : test_multiwidget.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def __init__(self, required=True, widget=None, label=None, initial=None):
        fields = (
            CharField(),
            MultipleChoiceField(choices=WidgetTest.beatles),
            SplitDateTimeField(),
        )
        super().__init__(fields, required, widget, label, initial)

3 View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
    def test_MaterialForm_materializes_MultipleChoiceField(self):
        """django.forms.widgets.SelectMultiple should be converted to
        material_widgets.widgets.MaterialSelectMultiple.
        """

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

        form = SelectMultipleForm()
        self.astertEqual(
            type(form.fields['select_multiple'].widget),
            widgets.MaterialSelectMultiple,
            )

3 View Complete Implementation : base.py
Copyright MIT License
Author : openfun
    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
            )
        }

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

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

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

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

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

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

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

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

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

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

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

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

            self.fields.pop('groups')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    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 pastword fields when editing
        if "instance" in kwargs:
            self.fields["pastword1"].required = False
            self.fields["pastword2"].required = False

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
    def __init__(self, *args, **kwargs):
        # get parameters
        self.event = kwargs.pop('event')
        self.user = kwargs.pop('user')

        # different select values

        # send to helpers and coordinators
        self.jobs_all = {}

        # only coordinators
        self.jobs_coordinators = {}

        # single shifts
        self.shifts = {}

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

        # get all allowed jobs
        choices = []

        # admins can send mails to all helpers
        if self.event.is_admin(self.user):
            tmp = []
            tmp.append(("all", _("All helpers and coordinators")))
            tmp.append(("all-coords", _("All coordinators")))

            choices.append((_("General"), tmp))

        for job in self.event.job_set.all():
            if job.is_admin(self.user):
                tmp = []

                # helpers and coordinators
                satle = _("{}, Helpers and coordinators").format(job.name)
                tmp.append(("job_%d_all" % job.pk, satle))
                self.jobs_all["job_%d_all" % job.pk] = job

                # only coordinators
                satle = _("{}, Coordinators").format(job.name)
                tmp.append(("job_%d_coords" % job.pk, satle))
                self.jobs_coordinators["job_%d_coords" % job.pk] = job

                # shifts
                for shift in job.shift_set.all():
                    tmp.append(("shift_%d" % shift.pk, str(shift)))
                    self.shifts["shift_%d" % shift.pk] = shift

                choices.append((job.name, tmp))

        # reply to
        reply_to = []

        if self.event.is_admin(self.user):
            reply_to.append((self.event.email, self.event.email))

        reply_to.append((self.user.email, self.user.email))
        reply_to.append(("-", _("Custom")))

        # fields
        self.fields['receiver'] = forms.MultipleChoiceField(
            choices=choices,
            label=_("Receivers"),
            widget=Select2MultipleWidget,
        )

        self.fields['reply_to'] = forms.ChoiceField(
            choices=reply_to,
            label=_("Reply to"),
        )
        self.fields['reply_to'].widget.attrs['onChange'] = 'handle_reply_to()'

        self.fields['custom_reply_to'] = forms.EmailField(
            label=_("Custom reply to"),
            help_text=_('Only used if "Custom" is selected above.'),
            required=False,
        )

        self.fields['cc'] = forms.EmailField(
            label=_("CC"),
            required=False,
        )

        self.fields['subject'] = forms.CharField(
            label=_("Subject"),
            max_length=200,
        )

        self.fields['text'] = forms.CharField(
            widget=forms.Textarea,
            label=_("Text"),
        )

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

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

0 View Complete Implementation : ephemeral.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _set_up_script_fields(self):
        testing_scripts = self.data.get("testing_scripts")
        if testing_scripts is not None and isinstance(testing_scripts, str):
            if isinstance(self.data, QueryDict):
                # QueryDict must have its value updated using setlist otherwise
                # it puts the set value inside a list.
                self.data.setlist(
                    "testing_scripts", testing_scripts.split(",")
                )
            else:
                self.data["testing_scripts"] = testing_scripts.split(",")

        choices = []
        scripts = Script.objects.filter(script_type=SCRIPT_TYPE.TESTING)
        for script in scripts:
            if script.script_type == SCRIPT_TYPE.TESTING:
                choices.append((script.name, script.name))
                for tag in script.tags:
                    choices.append((tag, tag))

        self.fields["testing_scripts"] = MultipleChoiceField(
            required=False, initial=None, choices=choices
        )
        self._set_up_parameter_fields(scripts)

0 View Complete Implementation : ephemeral.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _set_up_script_fields(self):
        # If a string was given convert into a list for validation and use.
        for script_field in ["commissioning_scripts", "testing_scripts"]:
            value = self.data.get(script_field)
            if value is not None and isinstance(value, str):
                if isinstance(self.data, QueryDict):
                    # QueryDict must have its value updated using setlist
                    # otherwise it puts the set value inside a list.
                    self.data.setlist(script_field, value.split(","))
                else:
                    self.data[script_field] = value.split(",")

        choices = {
            SCRIPT_TYPE.COMMISSIONING: [],
            SCRIPT_TYPE.TESTING: [("none", "none")],
        }
        scripts = Script.objects.all()
        for script in scripts:
            for script_type, script_choices in choices.items():
                if script.script_type == script_type:
                    script_choices.append((script.name, script.name))
                    for tag in script.tags:
                        script_choices.append((tag, tag))

        self.fields["commissioning_scripts"] = MultipleChoiceField(
            required=False,
            initial=None,
            choices=choices[SCRIPT_TYPE.COMMISSIONING],
        )
        self.fields["testing_scripts"] = MultipleChoiceField(
            required=False, initial=None, choices=choices[SCRIPT_TYPE.TESTING]
        )
        self._set_up_parameter_fields(scripts)

0 View Complete Implementation : test_multiplechoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiplechoicefield_1(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.astertEqual(['1'], f.clean([1]))
        self.astertEqual(['1'], f.clean(['1']))
        self.astertEqual(['1', '2'], f.clean(['1', '2']))
        self.astertEqual(['1', '2'], f.clean([1, '2']))
        self.astertEqual(['1', '2'], f.clean((1, '2')))
        with self.astertRaisesMessage(ValidationError, "'Enter a list of values.'"):
            f.clean('hello')
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean([])
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(())
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean(['3'])

0 View Complete Implementation : test_multiplechoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_disabled_has_changed(self):
        f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], disabled=True)
        self.astertIs(f.has_changed('x', 'y'), False)

0 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_error_messages_escaping(self):
        # The forms layer doesn't escape input values directly because error
        # messages might be presented in non-HTML contexts. Instead, the
        # message is marked for escaping by the template engine, so a template
        # is needed to trigger the escaping.
        t = Template('{{ form.errors }}')

        clast SomeForm(Form):
            field = ChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': '<script>'})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>Select a valid choice. <script> is not one of the '
            'available choices.</li></ul></li></ul>'
        )

        clast SomeForm(Form):
            field = MultipleChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': ['<script>']})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>Select a valid choice. <script> is not one of the '
            'available choices.</li></ul></li></ul>'
        )

        clast SomeForm(Form):
            field = ModelMultipleChoiceField(ChoiceModel.objects.all())

        f = SomeForm({'field': ['<script>']})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>"<script>" is not a valid value.</li>'
            '</ul></li></ul>'
        )

0 View Complete Implementation : form_factory.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def __init__(self, *args, **kwargs):
        saved_report_meta = kwargs.pop('form_settings', {})
        imposed_form_settings = kwargs.pop('imposed_form_settings', False)
        if imposed_form_settings and saved_report_meta:
            initial_settings = self.initial_settings.copy()
            initial_settings.update(saved_report_meta)
            saved_report_meta = initial_settings

        kwargs.pop('admin_state', False)
        data = QueryDict('', mutable=True)
        if 'data' in kwargs:

            data = kwargs.get('data', {}).copy()
            if '__doc_typeid__' in data:
                # inject __doc_typeid__
                # in place of doc_types to get the criteria in place like a boss
                doc_type_id = data.pop('__doc_typeid__')
                doc_type_id = '__doc_type_%s__' % doc_type_id[0]
                data.pop('doc_types', False)
                data.setlist('doc_types', [u'%s' % doc_type_id])

        if saved_report_meta:
            enforce = False
            for field in self.base_fields.keys():
                if field in saved_report_meta:
                    if type(self.base_fields[field]) == forms.MultipleChoiceField and not field == 'doc_types':
                        data.setlist(field, saved_report_meta[field] or [])
                    elif field in ['from_doc_date']:  # , 'to_doc_date']:

                        if hasattr(saved_report_meta[field], '_proxy____cast'):
                            _date = saved_report_meta[field]._proxy____cast()
                        elif type(saved_report_meta[field]) is datetime.datetime:
                            _date = saved_report_meta[field]
                        else:
                            _date = datetime.datetime.strptime(saved_report_meta[field], '%Y-%m-%d %H:%M:%S')
                            # _date = saved_report_meta[field].strptime(saved_report_meta[field],'%Y-%m-%d %H:%M:%S')
                        if 'from_doc_date_0' not in data:
                            data['from_doc_date_0'] = _date.date()

                        if 'from_doc_date_1' not in data:
                            data['from_doc_date_1'] = _date.time().strftime('%H:%M')

                    elif field in ['to_doc_date']:
                        _date = now()  # .strftime('%Y-%m-%d %H:%M:%S')
                        if 'to_doc_date_0' not in data:
                            data['to_doc_date_0'] = _date.date() + + datetime.timedelta(days=1)

                        if 'to_doc_date_1' not in data:
                            data['to_doc_date_1'] = datetime.time.min.strftime('%H:%M')

                    elif field == 'group_by':
                        if not saved_report_meta.get('can_edit_primary_index', False) or u'group_by' not in data:
                            data[field] = saved_report_meta[field]

                    elif field == 'aggregate_on':
                        if not saved_report_meta.get('can_edit_secondary_index',
                                                     False) or u'aggregate_on' not in data:
                            data[field] = saved_report_meta[field]

                    elif field == 'time_series_pattern':
                        if not saved_report_meta.get('can_edit_time_series_pattern',
                                                     False) or u'time_series_pattern' not in data:
                            data[field] = saved_report_meta[field]
                    elif field == 'matrix_show_other':
                        data[field] = saved_report_meta[field]
                    elif field == 'matrix_ensaties':
                        past
                    elif field == 'doc_types':
                        if not saved_report_meta.get('can_edit_doc_types',
                                                     False) or u'doc_types' not in data:
                            data.setlist(field, saved_report_meta[field])



                    else:

                        if field not in self.foreign_keys.keys():
                            data[field] = saved_report_meta[field]

        if data:
            kwargs['data'] = data

        if data['matrix']:
            from ra.admin.admin import ra_admin_site
            matrix_field = self.foreign_keys[data['matrix'] + '_id']
            formfield = matrix_field.formfield(
                **{'form_clast': forms.ModelMultipleChoiceField,
                   'required': False,
                   'widget': RaAutocompleteSelectMultiple(matrix_field.remote_field, ra_admin_site,
                                                          attrs={'clast': 'select2bs4'})})
            self.base_fields['matrix_ensaties'] = formfield

        super(BaseReportForm, self).__init__(*args, **kwargs)
        self.is_valid()

        self.helper = FormHelper()
        self.helper.form_clast = 'form-horizontal'
        self.helper.label_clast = 'col-sm-2 col-md-2 col-lg-1'
        self.helper.field_clast = 'col-sm-10 col-md-10 col-lg-11'
        self.helper.form_tag = True

        self.helper.layout = get_user_formLayout(self._fkeys, saved_report_meta, self)

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

        alert_types = get_alert_types()

        self.fields['event_type'] = forms.MultipleChoiceField(
            choices=get_event_types(),
            required=False
        )

        self.fields['alert_type'] = forms.MultipleChoiceField(
            choices=alert_types,
            required=False
        )
        self.fields['category'] = forms.MultipleChoiceField(
            choices=get_categories(),
            required=False
        )
        self.fields['organization'] = forms.MultipleChoiceField(
            choices=get_organizations(),
            required=False
        )
        self.fields['device_group'] = forms.MultipleChoiceField(
            choices=get_device_groups(),
            required=False
        )

        self.fields['location'] = forms.MultipleChoiceField(
            choices=get_locations(),
            required=False
        )

        self.fields['not_event_type'] = forms.MultipleChoiceField(
            choices=get_event_types(),
            required=False
        )
        self.fields['not_alert_type'] = forms.MultipleChoiceField(
            choices=alert_types,
            required=False
        )
        self.fields['not_category'] = forms.MultipleChoiceField(
            choices=get_categories(),
            required=False
        )
        self.fields['not_organization'] = forms.MultipleChoiceField(
            choices=get_organizations(),
            required=False
        )
        self.fields['not_device_group'] = forms.MultipleChoiceField(
            choices=get_device_groups(),
            required=False
        )
        self.fields['not_location'] = forms.MultipleChoiceField(
            choices=get_locations(),
            required=False
        )

        self.fields['status_filters'] = forms.MultipleChoiceField(
            choices=[(t, forms.forms.pretty_name(t))
                     for t, f in self.fields.items()
                     if isinstance(f, forms.MultipleChoiceField)],
            required=False,
            label='Choose fields to filter status by'
        )

        column_clast = 'medium-6'
        self.helper = FormHelper()
        self.helper.form_id = 'status-form'
        self.helper.form_action = ''
        self.helper.form_method = 'POST'
        self.helper.layout = Layout(
            Row(
                Column(
                    Field('status_filters', css_clast='select2'),
                    Fieldset(
                        'Status filters',
                        Field('alert_type', css_clast='select2'),
                        Field('category', css_clast='select2'),
                        Field('device_group', css_clast='select2'),
                        Field('event_type', css_clast='select2'),
                        Field('location', css_clast='select2'),
                        Field('organization', css_clast='select2'),
                        Field('not_alert_type', css_clast='select2'),
                        Field('not_category', css_clast='select2'),
                        Field('not_device_group', css_clast='select2'),
                        Field('not_event_type', css_clast='select2'),
                        Field('not_location', css_clast='select2'),
                        Field('not_organization', css_clast='select2'),
                        css_clast='field_list'),
                    css_clast=column_clast),
                Column('stateless', 'stateless_threshold',
                       'acknowledged', 'on_maintenance',
                       css_clast=column_clast),
            ),
            HTML('<hr>'),

        )