Python django.forms.CheckboxSelectMultiple() Examples

The following are 30 code examples for showing how to use django.forms.CheckboxSelectMultiple(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: select.py    License: 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 2
Project: SEMS   Author: urankajtazaj   File: forms.py    License: 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
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SiteBulkEditForm, self).__init__(*args, **kwargs)

        self.fields['sites'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=project.sites.all(),
        )

        for attr in project.site_meta_attributes:
            q_type = attr['question_type']
            q_name = attr['question_name']

            if q_type == 'Number':
                field = forms.FloatField()
            elif q_type == 'Date':
                field = forms.DateField()
            elif q_type == 'MCQ':
                options = attr.get('mcq_options') or []
                choices = [o.get('option_text') for o in options]
                choices = [(c, c) for c in choices]
                field = forms.ChoiceField(choices=choices)
            else:
                field = forms.CharField()

            self.fields[q_name] = field 
Example 4
Project: tom_base   Author: TOMToolkit   File: facility.py    License: 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()
        ) 
Example 5
Project: tom_base   Author: TOMToolkit   File: forms.py    License: 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 6
Project: osler   Author: SaturdayNeighborhoodHealthClinic   File: forms.py    License: 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 7
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: 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 8
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: 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 9
Project: wagtail   Author: wagtail   File: view_restrictions.py    License: 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 10
Project: Spirit   Author: nitely   File: forms.py    License: 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 11
Project: Spirit   Author: nitely   File: forms.py    License: MIT License 5 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 12
Project: wagtailstreamforms   Author: labd   File: test_hook_select_field.py    License: MIT License 5 votes vote down vote up
def test_formfield(self):
        field = self.get_field(HookSelectModel, "hooks")
        formfield = field.formfield()
        self.assertTrue(isinstance(formfield, HookMultiSelectFormField))
        self.assertTrue(isinstance(formfield.widget, CheckboxSelectMultiple))
        self.assertEqual(
            formfield.choices,
            [("save_form_submission_data", "Save form submission data")],
        ) 
Example 13
Project: eventoL   Author: eventoL   File: filters.py    License: 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 14
Project: eventoL   Author: eventoL   File: test_templatetag_filters.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_is_checkbox_with_CheckboxSelectMultiple_return_true(mocker):
    boundfield = mocker.Mock()
    boundfield.field = mocker.Mock()
    boundfield.field.widget = forms.CheckboxSelectMultiple()
    assert filters.is_checkbox(boundfield) 
Example 15
Project: connect   Author: nlhkabu   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ProfileForm, self).__init__(*args, **kwargs)

        self.fields['full_name'] = forms.CharField(
            max_length=30,
            initial=self.user.full_name,
            widget=forms.TextInput(attrs={
                'placeholder': _('Name'),
            }),
            error_messages={
                'required': _('Please enter your full name.')
            })

        self.fields['bio'] = forms.CharField(
            initial=self.user.bio,
            widget=forms.Textarea(attrs={
                'class': 'bio',
                'placeholder': _('Add some details about yourself...'),
                'rows': 'auto',
            }),
            required=False)

        roles = Role.objects.all()
        self.fields['roles'] = RoleModelMultipleChoiceField(
            initial=self.user.roles.all(),
            queryset=roles,
            widget=forms.CheckboxSelectMultiple(),
            required=False) 
Example 16
Project: callisto-core   Author: project-callisto   File: test_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_generates_checkbox(self):
        field = mocks.MockQuestion(self.question.serialized).make_field()
        self.assertEqual(len(field.choices), 5)
        self.assertEqual(field.choices[4][1], "This is choice 4")
        self.assertIsInstance(field.widget, forms.CheckboxSelectMultiple) 
Example 17
Project: open-humans   Author: OpenHumans   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Add custom handling for requested_sources and override some widgets.
        """
        super().__init__(*args, **kwargs)

        source_projects = DataRequestProject.objects.filter(approved=True).exclude(
            returned_data_description=""
        )
        self.fields["requested_sources"].choices = [
            (p.id, p.name) for p in source_projects
        ]
        self.fields["requested_sources"].widget = forms.CheckboxSelectMultiple()
        self.fields["requested_sources"].required = False

        override_fields = [
            "is_study",
            "is_academic_or_nonprofit",
            "active",
            "request_username_access",
        ]

        # XXX: feels like a hack; ideally we could just override the widget in
        # the Meta class but it doesn't work (you end up with an empty option)
        for field in override_fields:
            # set the widget to a RadioSelect
            self.fields[field].widget = forms.RadioSelect()

            # filter out the empty choice
            self.fields[field].choices = [
                choice for choice in self.fields[field].choices if choice[0] != ""
            ]

            # coerce the result to a boolean
            self.fields[field].coerce = lambda x: x == "True" 
Example 18
Project: hypha   Author: OpenTechFund   File: blocks.py    License: 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 19
Project: jeeves   Author: jeanqasaur   File: forms.py    License: 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
Project: jeeves   Author: jeanqasaur   File: forms.py    License: 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
Project: jeeves   Author: jeanqasaur   File: forms.py    License: 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
Project: jeeves   Author: jeanqasaur   File: forms.py    License: 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
Project: helfertool   Author: helfertool   File: helper.py    License: 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 24
Project: helfertool   Author: helfertool   File: helper.py    License: 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 25
Project: djongo   Author: nesdis   File: tests.py    License: 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 26
Project: djongo   Author: nesdis   File: tests.py    License: 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 27
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: 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 28
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: 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 29
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 30
Project: djongo   Author: nesdis   File: tests.py    License: 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')