Python django.forms.CheckboxSelectMultiple() Examples

The following are 30 code examples of django.forms.CheckboxSelectMultiple(). 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 Spirit with MIT License 7 votes vote down vote up
def __init__(self, topic, *args, **kwargs):
        super(CommentMoveForm, self).__init__(*args, **kwargs)
        self.fields['comments'] = forms.ModelMultipleChoiceField(
            queryset=Comment.objects.filter(topic=topic),
            widget=forms.CheckboxSelectMultiple
        ) 
Example #2
Source File: select.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):

        the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]]
        the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0]))

        initial = []

        if fieldsubmission:
            initial=fieldsubmission.data['info']

        c = self.CustomMultipleChoiceField(required=self.config['required'],
            label=self.config['label'],
            help_text=self.config['help_text'],
            choices=the_choices,
            widget=forms.CheckboxSelectMultiple(),
            initial=initial)

        return c 
Example #3
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 #4
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_widget(self, struct_value):
        if struct_value['multi']:
            category = struct_value['category']
            category_size = category.options.count()
            # Pick widget according to number of options to maintain good usability.
            if category_size < 32:
                return forms.CheckboxSelectMultiple
            else:
                return Select2MultipleWidget
        else:
            return forms.RadioSelect 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: helper.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.helper = kwargs.pop('helper')
        self.user = kwargs.pop('user')

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

        event = self.helper.event

        # field that contains all shifts if
        #  - user is admin for shift/job
        #  - helper is not already in this shift

        # all administered shifts
        administered_jobs = [job for job in event.job_set.all()
                             if job.is_admin(self.user)]
        shifts = Shift.objects.filter(job__event=event,
                                      job__in=administered_jobs)

        # exclude already taken shifts
        shifts = shifts.exclude(id__in=self.helper.shifts.all())

        # add field
        self.fields['shifts'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=shifts, required=True) 
Example #11
Source File: helper.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.helper = kwargs.pop('helper')
        self.user = kwargs.pop('user')

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

        event = self.helper.event

        # field that contains all jobs if
        #  - user is admin for job
        #  - helper is not already coordinator for this job

        # all administered jobs
        coordinated_jobs = self.helper.coordinated_jobs
        jobs = [job.pk for job in event.job_set.all()
                if job.is_admin(self.user) and job not in coordinated_jobs]

        # we need a queryset
        jobs = Job.objects.filter(pk__in=jobs)

        # add field
        self.fields['jobs'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=jobs, required=True) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default_not_populated_on_checkboxselectmultiple(self):
        class PubForm(forms.ModelForm):
            mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple)

            class Meta:
                model = PublicationDefaults
                fields = ('mode',)

        # Empty data doesn't use the model default because an unchecked
        # CheckboxSelectMultiple doesn't have a value in HTML form submission.
        mf1 = PubForm({})
        self.assertEqual(mf1.errors, {})
        m1 = mf1.save(commit=False)
        self.assertEqual(m1.mode, '')
        self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_field_22745(self):
        """
        #22745 -- Make sure that ModelMultipleChoiceField with
        CheckboxSelectMultiple widget doesn't produce unnecessary db queries
        when accessing its BoundField's attrs.
        """
        class ModelMultipleChoiceForm(forms.Form):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple)

        form = ModelMultipleChoiceForm()
        field = form['categories']  # BoundField
        template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
        with self.assertNumQueries(1):
            template.render(Context({'field': field})) 
Example #14
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choice_iterator_passes_model_to_widget(self):
        class CustomModelChoiceValue:
            def __init__(self, value, obj):
                self.value = value
                self.obj = obj

            def __str__(self):
                return str(self.value)

        class CustomModelChoiceIterator(ModelChoiceIterator):
            def choice(self, obj):
                value, label = super().choice(obj)
                return CustomModelChoiceValue(value, obj), label

        class CustomCheckboxSelectMultiple(CheckboxSelectMultiple):
            def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
                option = super().create_option(name, value, label, selected, index, subindex=None, attrs=None)
                # Modify the HTML based on the object being rendered.
                c = value.obj
                option['attrs']['data-slug'] = c.slug
                return option

        class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
            iterator = CustomModelChoiceIterator
            widget = CustomCheckboxSelectMultiple

        field = CustomModelMultipleChoiceField(Category.objects.all())
        self.assertHTMLEqual(
            field.widget.render('name', []),
            '''<ul>
<li><label><input type="checkbox" name="name" value="%d" data-slug="entertainment">Entertainment</label></li>
<li><label><input type="checkbox" name="name" value="%d" data-slug="test">A test</label></li>
<li><label><input type="checkbox" name="name" value="%d" data-slug="third-test">Third</label></li>
</ul>''' % (self.c1.pk, self.c2.pk, self.c3.pk),
        ) 
Example #15
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_num_queries(self):
        """
        Widgets that render multiple subwidgets shouldn't make more than one
        database query.
        """
        categories = Category.objects.all()

        class CategoriesForm(forms.Form):
            radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
            checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)

        template = Template(
            '{% for widget in form.checkbox %}{{ widget }}{% endfor %}'
            '{% for widget in form.radio %}{{ widget }}{% endfor %}'
        )
        with self.assertNumQueries(2):
            template.render(Context({'form': CategoriesForm()})) 
Example #16
Source File: test_checkboxselectmultiple.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_separate_ids_constructor(self):
        """
        Each input gets a separate ID when the ID is passed to the constructor.
        """
        widget = CheckboxSelectMultiple(attrs={'id': 'abc'}, choices=[('a', 'A'), ('b', 'B'), ('c', 'C')])
        html = """
        <ul id="abc">
        <li>
        <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
        </li>
        <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></li>
        <li>
        <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
        </li>
        </ul>
        """
        self.check_html(widget, 'letters', ['a', 'c'], html=html) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default_not_populated_on_checkboxselectmultiple(self):
        class PubForm(forms.ModelForm):
            mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple)

            class Meta:
                model = PublicationDefaults
                fields = ('mode',)

        # Empty data doesn't use the model default because an unchecked
        # CheckboxSelectMultiple doesn't have a value in HTML form submission.
        mf1 = PubForm({})
        self.assertEqual(mf1.errors, {})
        m1 = mf1.save(commit=False)
        self.assertEqual(m1.mode, '')
        self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_field_22745(self):
        """
        #22745 -- Make sure that ModelMultipleChoiceField with
        CheckboxSelectMultiple widget doesn't produce unnecessary db queries
        when accessing its BoundField's attrs.
        """
        class ModelMultipleChoiceForm(forms.Form):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple)

        form = ModelMultipleChoiceForm()
        field = form['categories']  # BoundField
        template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
        with self.assertNumQueries(1):
            template.render(Context({'field': field})) 
Example #19
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choice_iterator_passes_model_to_widget(self):
        class CustomModelChoiceValue:
            def __init__(self, value, obj):
                self.value = value
                self.obj = obj

            def __str__(self):
                return str(self.value)

        class CustomModelChoiceIterator(ModelChoiceIterator):
            def choice(self, obj):
                value, label = super().choice(obj)
                return CustomModelChoiceValue(value, obj), label

        class CustomCheckboxSelectMultiple(CheckboxSelectMultiple):
            def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
                option = super().create_option(name, value, label, selected, index, subindex=None, attrs=None)
                # Modify the HTML based on the object being rendered.
                c = value.obj
                option['attrs']['data-slug'] = c.slug
                return option

        class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
            iterator = CustomModelChoiceIterator
            widget = CustomCheckboxSelectMultiple

        field = CustomModelMultipleChoiceField(Category.objects.all())
        self.assertHTMLEqual(
            field.widget.render('name', []),
            '''<ul>
<li><label><input type="checkbox" name="name" value="%d" data-slug="entertainment">Entertainment</label></li>
<li><label><input type="checkbox" name="name" value="%d" data-slug="test">A test</label></li>
<li><label><input type="checkbox" name="name" value="%d" data-slug="third-test">Third</label></li>
</ul>''' % (self.c1.pk, self.c2.pk, self.c3.pk),
        ) 
Example #20
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_num_queries(self):
        """
        Widgets that render multiple subwidgets shouldn't make more than one
        database query.
        """
        categories = Category.objects.all()

        class CategoriesForm(forms.Form):
            radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
            checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)

        template = Template(
            '{% for widget in form.checkbox %}{{ widget }}{% endfor %}'
            '{% for widget in form.radio %}{{ widget }}{% endfor %}'
        )
        with self.assertNumQueries(2):
            template.render(Context({'form': CategoriesForm()})) 
Example #21
Source File: test_checkboxselectmultiple.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_separate_ids_constructor(self):
        """
        Each input gets a separate ID when the ID is passed to the constructor.
        """
        widget = CheckboxSelectMultiple(attrs={'id': 'abc'}, choices=[('a', 'A'), ('b', 'B'), ('c', 'C')])
        html = """
        <ul id="abc">
        <li>
        <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
        </li>
        <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></li>
        <li>
        <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
        </li>
        </ul>
        """
        self.check_html(widget, 'letters', ['a', 'c'], html=html) 
Example #22
Source File: forms.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)

        self.fields["categories"].widget = forms.CheckboxSelectMultiple()

        title_field = layout.Field("title")
        content_field = layout.Field("content", rows="3")
        main_fieldset = layout.Fieldset(_("Main data"), title_field, content_field)

        picture_field = layout.Field("picture")
        format_html = layout.HTML(
            """{% include "ideas2/includes/picture_guidelines.html" %}"""
        )

        picture_fieldset = layout.Fieldset(
            _("Picture"),
            picture_field,
            format_html,
            title=_("Image upload"),
            css_id="picture_fieldset",
        )

        categories_field = layout.Field("categories")
        categories_fieldset = layout.Fieldset(
            _("Categories"), categories_field, css_id="categories_fieldset"
        )

        submit_button = layout.Submit("save", _("Save"))
        actions = bootstrap.FormActions(submit_button)

        self.helper = helper.FormHelper()
        self.helper.form_action = self.request.path
        self.helper.form_method = "POST"
        self.helper.layout = layout.Layout(
            main_fieldset,
            picture_fieldset,
            categories_fieldset,
            actions,
        ) 
Example #23
Source File: djangocms_forms_tags.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_checkboxselectmultiple(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple) 
Example #24
Source File: filters.py    From eventoL with GNU General Public License v3.0 5 votes vote down vote up
def is_checkbox(boundfield):
    """Return True if this field's widget is a CheckboxInput."""
    widget = boundfield.field.widget
    is_checkbox_input = isinstance(widget, forms.CheckboxInput)
    is_checkbox_select = isinstance(widget, forms.CheckboxSelectMultiple)
    return is_checkbox_input or is_checkbox_select 
Example #25
Source File: forms.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, referral_location_qs, *args, **kwargs):
        super(ReferralForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.fields['location'].widget = forms.widgets.CheckboxSelectMultiple()
        self.fields['location'].queryset = referral_location_qs
        self.helper.add_input(Submit('submit', 'Create referral')) 
Example #26
Source File: forms.py    From janeway with 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 #27
Source File: forms.py    From janeway with 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 #28
Source File: forms.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not settings.TARGET_PERMISSIONS_ONLY:
            self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
                                                                   required=False,
                                                                   widget=forms.CheckboxSelectMultiple) 
Example #29
Source File: view_restrictions.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['groups'].widget = forms.CheckboxSelectMultiple()
        self.fields['groups'].queryset = Group.objects.all() 
Example #30
Source File: facility.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        if settings.TARGET_PERMISSIONS_ONLY:
            self.common_layout = Layout('facility', 'target_id', 'observation_type')
        else:
            self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
                                                                   required=False,
                                                                   widget=forms.CheckboxSelectMultiple)
            self.common_layout = Layout('facility', 'target_id', 'observation_type', 'groups')
        self.helper.layout = Layout(
            self.common_layout,
            self.layout(),
            self.button_layout()
        )