Python django.forms 模块,CheckboxSelectMultiple() 实例源码

我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用django.forms.CheckboxSelectMultiple()

项目:stoicism    作者:srgpdbd    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        extra_field = kwargs.pop('extra')
        # create dict appropriate for MultipleChoiceField
        # like {question: [[option:option]]}
        extra_fields = {}
        for key in extra_field.keys():
            options = []
            # unpack QuerySet
            for answer_option in extra_field[key]:
                options.append((answer_option.option, answer_option.option))
            extra_fields[key] = options
        super(forms.Form, self).__init__(*args, **kwargs)
        for i, question in enumerate(extra_fields.keys()):
            # add answer options to fields
            self.fields['question_%s' % i] = forms.MultipleChoiceField(
                label=question,
                widget=forms.CheckboxSelectMultiple,
                choices=extra_fields[question]
                )
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def __init__(self, *args, poll, **kwargs):
        super().__init__(*args, **kwargs)
        self.poll = poll
        self.helper = FormHelper()

        if 'options' in self.poll.rules and self.poll.rules['options'] == 1:
            self.fields['choice'] = ModelChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=RadioSelect,
                required=True,
                empty_label=None,
                initial=None,
            )
        else:
            self.fields['choice'] = ModelMultipleChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=CheckboxSelectMultiple(),
            )

        self.helper.add_input(Submit('submit', 'Confirmer'))
项目:mes    作者:osess    | 项目源码 | 文件源码
def test_custom_django_widget(self):
        class CustomRadioSelect(forms.RadioSelect):
            pass

        class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
            pass

        # Make sure an inherited RadioSelect gets rendered as it
        form = CheckboxesTestForm()
        form.fields['inline_radios'].widget = CustomRadioSelect()
        form.helper = FormHelper()
        form.helper.layout = Layout('inline_radios')

        html = render_crispy_form(form)
        self.assertTrue('class="radio"' in html)

        # Make sure an inherited CheckboxSelectMultiple gets rendered as it
        form.fields['checkboxes'].widget = CustomCheckboxSelectMultiple()
        form.helper.layout = Layout('checkboxes')
        html = render_crispy_form(form)
        self.assertTrue('class="checkbox"' in html)
项目:helfertool    作者:helfertool    | 项目源码 | 文件源码
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)
项目:helfertool    作者:helfertool    | 项目源码 | 文件源码
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)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def is_checkbox_select_multiple(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def _get_product_attributes_filters(self):
        filters = {}
        for attribute in self.product_attributes:
            filters[attribute.slug] = MultipleChoiceFilter(
                name='attributes__%s' % attribute.pk,
                label=attribute.name,
                widget=CheckboxSelectMultiple,
                choices=self._get_attribute_choices(attribute))
        return filters
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def _get_product_variants_attributes_filters(self):
        filters = {}
        for attribute in self.variant_attributes:
            filters[attribute.slug] = MultipleChoiceFilter(
                name='variants__attributes__%s' % attribute.pk,
                label=attribute.name,
                widget=CheckboxSelectMultiple,
                choices=self._get_attribute_choices(attribute))
        return filters
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
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)
项目:wagtailsurveys    作者:torchbox    | 项目源码 | 文件源码
def test_fields(self):
        """
        This tests that all fields were added to the form with the correct types
        """
        form_class = self.fb.get_form_class()

        field_names = form_class.base_fields.keys()

        # All fields are present in form
        self.assertIn('your-name', field_names)
        self.assertIn('your-biography', field_names)
        self.assertIn('your-birthday', field_names)
        self.assertIn('your-birthtime', field_names)
        self.assertIn('your-email', field_names)
        self.assertIn('your-homepage', field_names)
        self.assertIn('your-favourite-number', field_names)
        self.assertIn('your-favourite-python-ides', field_names)
        self.assertIn('your-favourite-python-ide', field_names)
        self.assertIn('your-choices', field_names)
        self.assertIn('i-agree-to-the-terms-of-use', field_names)

        # All fields have proper type
        self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField)
        self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField)
        self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField)
        self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField)
        self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField)
        self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField)

        # Some fields have non-default widgets
        self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect)
        self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
项目:moore    作者:UTNkar    | 项目源码 | 文件源码
def get_edit_handler_class(self):
        edit_handler = TabbedInterface([
            ObjectList([
                FieldPanel('name_en'),
                FieldPanel('name_sv'),
                FieldPanel('degree'),
            ], heading=_('General'),
            ),
            # TODO: http://stackoverflow.com/questions/43188124/
            # ObjectList([
            #     FieldPanel('sections', widget=CheckboxSelectMultiple),
            # ], heading=_('Sections'),
            # ),
        ])
        return edit_handler.bind_to_model(self.model)
项目:moore    作者:UTNkar    | 项目源码 | 文件源码
def get_edit_handler_class(self):
        edit_handler = TabbedInterface([
            ObjectList([
                FieldPanel('name_en'),
                FieldPanel('name_sv'),
                FieldPanel('abbreviation'),
            ], heading=_('General'), ),
            ObjectList([
                FieldPanel('studies', widget=CheckboxSelectMultiple),
            ], heading=_('Studies'), ),
        ])
        return edit_handler.bind_to_model(self.model)
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def is_multiple_checkbox(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def is_multiple_checkbox(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)
项目:django-wizard-builder    作者:project-callisto    | 项目源码 | 文件源码
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)
项目:django-daiquiri    作者:aipescience    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)

        # add a field for each detail key
        for detail_key in settings.AUTH_DETAIL_KEYS:

            choices = [(option['id'], option['label']) for option in detail_key['options']]

            if detail_key['data_type'] == 'text':
                field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'textarea':
                field = forms.CharField(widget=forms.Textarea(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'select':
                field = forms.ChoiceField(choices=choices)
            elif detail_key['data_type'] == 'radio':
                field = forms.ChoiceField(choices=choices, widget=forms.RadioSelect)
            elif detail_key['data_type'] == 'multiselect':
                field = forms.MultipleChoiceField(choices=choices)
            elif detail_key['data_type'] == 'checkbox':
                field = forms.MultipleChoiceField(choices=choices, widget=forms.CheckboxSelectMultiple)
            else:
                raise Exception('Unknown detail key data type.')

            if 'label' in detail_key:
                field.label = detail_key['label']

            if 'required' in detail_key:
                field.required = detail_key['required']

            if 'help_text' in detail_key:
                field.help_text = detail_key['help_text']

            if self.instance.details and detail_key['key'] in self.instance.details:
                field.initial = self.instance.details[detail_key['key']]

            self.fields[detail_key['key']] = field
项目:alterchef    作者:libremesh    | 项目源码 | 文件源码
def _create_ssh_keys_field(data, kwargs, user):
    HT = _(u"<span class='text-warning'>WARNING: if any key is selected, telnet access will be disabled. If unsure leave all boxes unchecked.</span>")
    kwds = {}
    instance = kwargs.get('instance', None)
    if instance:
        network = instance.network
    elif data:
        network = data.get("network")
    else:
        network = kwargs.get("initial").get("network") if "initial" in kwargs else None
    if network and not hasattr(network, "pk"):
        network = Network.objects.get(id=int(network))

    if network:
        kwds["user__in"] = network.users
    else:
        kwds["user"] = user
    ssh_keys = SSHKey.objects.filter(**kwds)

    initial = []
    if not instance:
        # select auto_add keys only if the current user has an auto_add key
        # to avoid creating firmwares where the owner cannot SSH in
        user_auto_add_key = ssh_keys.filter(user=user, auto_add=True)
        if user_auto_add_key:
            initial = [s.pk for s in ssh_keys.filter(auto_add=True)]

    return forms.ModelMultipleChoiceField(
        queryset=ssh_keys, widget=forms.CheckboxSelectMultiple,
        help_text=HT, required=False, initial=initial)
项目:mes    作者:osess    | 项目源码 | 文件源码
def is_checkboxselectmultiple(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def get_field(self, *, question, initial, initial_object, readonly):
        if question.variant == QuestionVariant.BOOLEAN:
            # For some reason, django-bootstrap4 does not set the required attribute
            # itself.
            widget = forms.CheckboxInput(attrs={'required': 'required'}) if question.required else forms.CheckboxInput()
            initialbool = (initial == 'True') if initial else bool(question.default_answer)

            return forms.BooleanField(
                disabled=readonly, help_text=question.help_text,
                label=question.question, required=question.required,
                widget=widget, initial=initialbool
            )
        elif question.variant == QuestionVariant.NUMBER:
            return forms.DecimalField(
                disabled=readonly, help_text=question.help_text,
                label=question.question, required=question.required,
                min_value=Decimal('0.00'), initial=initial
            )
        elif question.variant == QuestionVariant.STRING:
            return forms.CharField(
                disabled=readonly, help_text=question.help_text,
                label=question.question, required=question.required, initial=initial
            )
        elif question.variant == QuestionVariant.TEXT:
            return forms.CharField(
                label=question.question, required=question.required,
                widget=forms.Textarea,
                disabled=readonly, help_text=question.help_text,
                initial=initial
            )
        elif question.variant == QuestionVariant.FILE:
            return forms.FileField(
                label=question.question, required=question.required,
                disabled=readonly, help_text=question.help_text,
                initial=initial
            )
        elif question.variant == QuestionVariant.CHOICES:
            return forms.ModelChoiceField(
                queryset=question.options.all(),
                label=question.question, required=question.required,
                initial=initial_object.options.first() if initial_object else question.default_answer,
                disabled=readonly, help_text=question.help_text,
            )
        elif question.variant == QuestionVariant.MULTIPLE:
            return forms.ModelMultipleChoiceField(
                queryset=question.options.all(),
                label=question.question, required=question.required,
                widget=forms.CheckboxSelectMultiple,
                initial=initial_object.options.all() if initial_object else question.default_answer,
                disabled=readonly, help_text=question.help_text,
            )
项目:frisbeer-backend    作者:Moetto    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['players'] = forms.MultipleChoiceField(
            choices=[(player.id, player.name) for player in list(Player.objects.all())],
            validators=[validate_players],
            widget=forms.CheckboxSelectMultiple)
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        user = kwargs.pop('user',None)
        months = kwargs.pop('months',[])
        recentseries = kwargs.pop('recentseries',[])
        customers = kwargs.pop('customers',[])

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

        if customers:
            self.fields['customers'] = forms.MultipleChoiceField(
                required=True,
                label=_('Selected customers'),
                widget=forms.CheckboxSelectMultiple(),
                choices=[(x.id,'%s <%s>' % (x.fullName, x.email)) for x in customers]
            )
            self.fields['customers'].initial = [x.id for x in customers]
            self.fields.pop('month',None)
            self.fields.pop('series',None)
            self.fields.pop('sendToSet',None)

            # Move the customer list to the top of the form
            self.fields.move_to_end('customers',last=False)

        else:
            self.fields['month'].choices = months
            self.fields['series'].choices = recentseries

        if user:
            self.fields['template'].queryset = EmailTemplate.objects.filter(Q(groupRequired__isnull=True) | Q(groupRequired__in=user.groups.all())).filter(hideFromForm=False)
项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def __init__(self, users, *args, **kwargs):
        super(GroupAddForm, self).__init__(*args, **kwargs)
        self.fields['users'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                         choices=users)
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, event, *args, **kwargs):
        super(OptionsForm, self).__init__(*args, **kwargs)
        self.fields['conference_options'] = forms.MultipleChoiceField(
            choices=[(option.id, str(option)) for
                     option in EventOptions.objects.filter(event=event)],
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'form-control'}
            )
        )