Python django.forms.BooleanField() Examples

The following are 30 code examples of django.forms.BooleanField(). 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 heltour with MIT License 7 votes vote down vote up
def __init__(self, league, player, *args, **kwargs):
        super(NotificationsForm, self).__init__(*args, **kwargs)
        for type_, _ in PLAYER_NOTIFICATION_TYPES:
            setting = PlayerNotificationSetting.get_or_default(player=player, league=league,
                                                               type=type_)
            self.fields[type_ + "_lichess"] = forms.BooleanField(required=False, label="Lichess",
                                                                 initial=setting.enable_lichess_mail)
            self.fields[type_ + "_slack"] = forms.BooleanField(required=False, label="Slack",
                                                               initial=setting.enable_slack_im)
            self.fields[type_ + "_slack_wo"] = forms.BooleanField(required=False,
                                                                  label="Slack (with opponent)",
                                                                  initial=setting.enable_slack_mpim)
            if type_ == 'before_game_time':
                offset_options = [(5, '5 minutes'), (10, '10 minutes'), (20, '20 minutes'),
                                  (30, '30 minutes'), (60, '1 hour'), (120, '2 hours')]
                self.fields[type_ + '_offset'] = forms.TypedChoiceField(choices=offset_options,
                                                                        initial=int(
                                                                            setting.offset.total_seconds()) / 60,
                                                                        coerce=int) 
Example #2
Source File: subscribe.py    From helfertool with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SubscribeForm, self).__init__(*args, **kwargs)

        # error message for existing mail address
        self.fields['email'].error_messages['unique'] = _("You subscribed already to the newsletter.")

        # privacy statement
        privacy_label = format_html(
            '{} (<a href="" data-toggle="collapse" data-target="#privacy">{}</a>)',
            _("I agree with the data privacy statement."),
            _("Show"),
        )
        privacy_error = _("You have to accept the data privacy statement.")

        self.fields['privacy_statement'] = forms.BooleanField(
            label=privacy_label,
            required=True,
            error_messages={'required': privacy_error},
        ) 
Example #3
Source File: forms.py    From firefox-profilemaker with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ConfigForm, self).__init__(*args, **kwargs)
        self.fields['form_name'] = forms.CharField(initial=self.id, widget=forms.widgets.HiddenInput)
        for option in self.options:
            if option['type'] == "boolean":
                self.fields[option['name']] = forms.BooleanField(
                    label=option['label'],
                    help_text=option['help_text'],
                    initial=option['initial'], required=False)
            if option['type'] == "choice":
                choices = option['choices']
                self.fields[option['name']] = forms.ChoiceField(
                    label=option['label'],
                    help_text=option['help_text'],
                    choices = list(zip(list(range(len(choices))), choices)),
                    initial=option['initial'], required=False)
            elif option['type'] == "text":
                self.fields[option['name']] = forms.CharField(
                    label=option['label'],
                    help_text=option['help_text'],
                    initial=option['initial'], required=False) 
Example #4
Source File: fields.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, extension, *args, **kwargs):
        self.extension = extension
        kwargs.setdefault('label', extension.name)
        ext = profile.extensions.get(self.extension.key)
        if ext:
            ext = ext.serialize()
            kwargs.setdefault('initial', [ext['value'], ext['critical']])

        fields = (
            forms.MultipleChoiceField(required=False, choices=extension.CHOICES),
            forms.BooleanField(required=False),
        )

        widget = MultiValueExtensionWidget(choices=extension.CHOICES)
        super(MultiValueExtensionField, self).__init__(
            fields=fields, require_all_fields=False, widget=widget,
            *args, **kwargs) 
Example #5
Source File: forms_json.py    From starthinker with Apache License 2.0 6 votes vote down vote up
def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c,c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False) 
Example #6
Source File: tests.py    From TWLight with MIT License 6 votes vote down vote up
def test_editor_optional_fields_match_field_type(self):
        """
        The optional user data fields on Editor should correspond to the
        FIELD_TYPES used on the application form. Additionally, each should
        allow blank=True (since not all instances require all data), except for
        BooleanFields, which should default False (i.e. they should default to
        not requiring the data).
        """
        for field in USER_FORM_FIELDS:
            # Ensure Editor fields allow for empty data.
            if not isinstance(Editor._meta.get_field(field), models.BooleanField):
                self.assertTrue(Editor._meta.get_field(field).blank)
            else:
                self.assertFalse(Editor._meta.get_field(field).default)

            # Make sure the form fields we're using match what the model fields
            # can record.
            modelfield = Editor._meta.get_field(field)
            formfield = modelfield.formfield()

            self.assertEqual(type(formfield), type(FIELD_TYPES[field])) 
Example #7
Source File: forms.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
def to_python(self, value):
        """Returns a Python boolean object.

        It is necessary to customize the behavior because the default
        ``BooleanField`` treats the string '0' as ``False``, but if the
        unit is in ``UNTRANSLATED`` state (which would report '0' as a
        value), we need the marked checkbox to be evaluated as ``True``.

        :return: ``False`` for any unknown :cls:`~pootle_store.models.Unit`
            states and for the 'False' string.
        """
        truthy_values = (str(s) for s in (UNTRANSLATED, FUZZY, TRANSLATED))
        if isinstance(value, str) and (
            value.lower() == "false" or value not in truthy_values
        ):
            value = False
        else:
            value = bool(value)

        return super().to_python(value) 
Example #8
Source File: forms.py    From fermentrack with MIT License 6 votes vote down vote up
def set_choices(self, family):
        # There's probably a better way of doing this
        board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family=family)]

        self.fields['board_type'].choices = board_choices


# class GuidedDeviceFlashForm(forms.Form):
#     DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES
#
#     device_family = forms.ChoiceField(label="Device Family",
#                                       widget=forms.Select(attrs={'class': 'form-control',
#                                                                  'data-toggle': 'select'}),
#                                       choices=DEVICE_FAMILY_CHOICES, required=True)
#     should_flash_device = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False)
#
# 
Example #9
Source File: forms.py    From zentral with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        field_order = [
            "virtual_server", "name",
            "allow_pairing", "is_supervised", "is_mandatory", "is_mdm_removable",
            "await_device_configured", "auto_advance_setup",
            "support_phone_number", "support_email_address",
            "org_magic", "department", "include_tls_certificates"
        ]
        for pane, initial in self.Meta.model.SKIPPABLE_SETUP_PANES:
            if self.instance.pk:
                initial = pane in self.instance.skip_setup_items
            self.fields[pane] = forms.BooleanField(label="Skip {} pane".format(pane), initial=initial, required=False)
            field_order.append(pane)
        field_order.extend(["realm", "use_realm_user", "realm_user_is_admin",
                            "admin_full_name", "admin_short_name", "admin_password"])
        self.order_fields(field_order) 
Example #10
Source File: tests.py    From TWLight with MIT License 5 votes vote down vote up
def test_form_class(self):
        """
        Ensure that the form created by RequestApplicationView has one
        BooleanField per Partner in the database, to allow Editors to select
        the ones they wish to apply for.
        """
        view = self._get_isolated_view(views.RequestApplicationView)

        # Make sure we've zeroed out the Partners, so we have the number we
        # expect.
        for partner in Partner.objects.all():
            partner.delete()

        # Check that it works with only one Partner in the database.
        partner = PartnerFactory()

        form_class = view.get_form_class()
        form = form_class()
        self.assertEqual(len(form.fields), 1)

        fieldkey = "partner_{id}".format(id=partner.id)
        self.assertIn(fieldkey, form.fields)
        assert isinstance(form.fields[fieldkey], forms.BooleanField)

        # Add Partners and see how many form fields there are. We'll assume
        # that they're all of the correct type, having tested that the first
        # one is.
        _ = PartnerFactory()
        _ = PartnerFactory()
        _ = PartnerFactory()

        form_class = view.get_form_class()
        form = form_class()
        self.assertEqual(len(form.fields), 4)

        # Add BUNDLE partners and ensure the form fields remain intact
        PartnerFactory(authorization_method=Partner.BUNDLE)
        form_class = view.get_form_class()
        form = form_class()
        self.assertEqual(len(form.fields), 4) 
Example #11
Source File: fields.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = (
            forms.CharField(required=False),
            forms.BooleanField(required=False),
        )
        kwargs.setdefault('widget', SubjectAltNameWidget)
        kwargs.setdefault('initial', ['', profile.cn_in_san])
        super(SubjectAltNameField, self).__init__(
            fields=fields, require_all_fields=False, *args, **kwargs) 
Example #12
Source File: forms.py    From registrasion with Apache License 2.0 5 votes vote down vote up
def set_fields(cls, category, products):
        for product in products:
            field = forms.BooleanField(
                label='%s -- %s' % (product.name, product.price),
                required=False,
            )
            cls.base_fields[cls.field_name(product)] = field 
Example #13
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['blank'] = True
        super(BooleanField, self).__init__(*args, **kwargs) 
Example #14
Source File: defaults.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')

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

        # available roles and designs
        roles = BadgeRole.objects.filter(
            badge_settings=self.event.badge_settings.pk)
        designs = BadgeDesign.objects.filter(
            badge_settings=self.event.badge_settings.pk)

        # add fields for each job
        for job in self.event.job_set.all():
            self.fields['job_%d_design' % job.pk] = forms.ModelChoiceField(
                queryset=designs, required=False,
                initial=job.badge_defaults.design)
            self.fields['job_%d_role' % job.pk] = forms.ModelChoiceField(
                queryset=roles, required=False,
                initial=job.badge_defaults.role)
            self.fields['job_%d_no_def_role' % job.pk] = forms.BooleanField(
                initial=job.badge_defaults.no_default_role,
                required=False,
                label=_("No default role"))

        if self.event.archived:
            for field_id in self.fields:
                self.fields[field_id].disabled = True 
Example #15
Source File: forms.py    From logtacts with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        tag_ids = kwargs.pop('tag_ids')
        super(MultiTagForm, self).__init__(*args, **kwargs)
        for tag_id in tag_ids:
            self.fields['tag_%s' % (tag_id,)] = forms.BooleanField(required=False) 
Example #16
Source File: forms.py    From superbook2 with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        vip = kwargs.pop("vip", False)
        super().__init__(*args, **kwargs)

        # Are you a VIP?
        if vip:
            self.fields["first_class"] = forms.BooleanField(
                label="Fly First Class?",
                required=False,
                initial=True,
                help_text="First-class only offered to VIPs")

        self.helper = FormHelper(self)
        self.helper.layout.append(Submit('submit', 'Submit')) 
Example #17
Source File: tests.py    From TWLight with MIT License 5 votes vote down vote up
def test_partner_optional_fields_are_boolean(self):
        """
        The optional user and partner data fields on Partner should be
        booleans, allowing each instance to indicate whether (True/False) it
        requires that data.
        """
        optional_fields = USER_FORM_FIELDS + PARTNER_FORM_OPTIONAL_FIELDS
        for field in optional_fields:
            self.assertTrue(
                isinstance(Partner._meta.get_field(field), models.BooleanField)
            ) 
Example #18
Source File: tests.py    From TWLight with MIT License 5 votes vote down vote up
def test_application_optional_fields_match_field_type(self):
        """
        The optional partner-specific data fields on Application should
        correspond to the FIELD_TYPES used on the form. Additionally, each
        should allow blank=True (since not all instances require all data),
        except for BooleanFields, which should default False (i.e. they should
        default to not requiring the data).
        """
        for field in PARTNER_FORM_OPTIONAL_FIELDS:
            # Ensure Application fields allow for empty data.
            if not isinstance(Application._meta.get_field(field), models.BooleanField):
                self.assertTrue(Application._meta.get_field(field).blank)
            else:
                self.assertFalse(Application._meta.get_field(field).default)

            # Make sure the form fields we're using match what the model fields
            # can record.
            modelfield = Application._meta.get_field(field)
            formfield = modelfield.formfield()

            # While we simply use the ChoiceField for requested_access_duration field in the form, the model makes use
            # of the TypedChoiceField, triggering a mismatch. We'll get around this by separately testing the fields.
            if field == "requested_access_duration":
                self.assertEqual(type(formfield), forms.TypedChoiceField)
                self.assertEqual(type(FIELD_TYPES[field]), forms.ChoiceField)
                break

            self.assertEqual(type(formfield), type(FIELD_TYPES[field])) 
Example #19
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(BooleanField, self).get_prep_value(value)
        if value is None:
            return None
        return self.to_python(value) 
Example #20
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Unlike most fields, BooleanField figures out include_blank from
        # self.null instead of self.blank.
        if self.choices:
            include_blank = not (self.has_default() or 'initial' in kwargs)
            defaults = {'choices': self.get_choices(include_blank=include_blank)}
        else:
            defaults = {'form_class': forms.BooleanField}
        defaults.update(kwargs)
        return super(BooleanField, self).formfield(**defaults) 
Example #21
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_prep_lookup(self, lookup_type, value):
        # Special-case handling for filters coming from a Web request (e.g. the
        # admin interface). Only works for scalar values (not lists). If you're
        # passing in a list, you might as well make things the right type when
        # constructing the list.
        if value in ('1', '0'):
            value = bool(int(value))
        return super(BooleanField, self).get_prep_lookup(lookup_type, value) 
Example #22
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_internal_type(self):
        return "BooleanField" 
Example #23
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(BooleanField, self).deconstruct()
        del kwargs['blank']
        return name, path, args, kwargs 
Example #24
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(BooleanField, self).check(**kwargs)
        errors.extend(self._check_null(**kwargs))
        return errors 
Example #25
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['blank'] = True
        super(BooleanField, self).__init__(*args, **kwargs) 
Example #26
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Unlike most fields, BooleanField figures out include_blank from
        # self.null instead of self.blank.
        if self.choices:
            include_blank = (self.null or
                             not (self.has_default() or 'initial' in kwargs))
            defaults = {'choices': self.get_choices(
                                       include_blank=include_blank)}
        else:
            defaults = {'form_class': forms.BooleanField}
        defaults.update(kwargs)
        return super(BooleanField, self).formfield(**defaults) 
Example #27
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_prep_lookup(self, lookup_type, value):
        # Special-case handling for filters coming from a Web request (e.g. the
        # admin interface). Only works for scalar values (not lists). If you're
        # passing in a list, you might as well make things the right type when
        # constructing the list.
        if value in ('1', '0'):
            value = bool(int(value))
        return super(BooleanField, self).get_prep_lookup(lookup_type, value) 
Example #28
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "BooleanField" 
Example #29
Source File: workflow.py    From ontask_b with MIT License 5 votes vote down vote up
def __init__(self, *args, **kargs):
        """Set actions, prefix and labels.

        Kargs contain: actions: list of action objects, put_labels: boolean
        stating if the labels should be included in the form

        :param args:
        :param kargs: Additional arguments such as list  of actions,
        field_prefix
        """
        # List of columns to process and a field prefix
        self.actions = kargs.pop('actions', [])
        self.field_prefix = kargs.pop('field_prefix', 'select_')

        # Should the labels be included?
        self.put_labels = kargs.pop('put_labels')

        super().__init__(*args, **kargs)

        # Create as many fields as the given columns
        for idx, action in enumerate(self.actions):
            # Include the labels if requested
            if self.put_labels:
                label = action.name
            else:
                label = ''

            self.fields[self.field_prefix + '%s' % idx] = forms.BooleanField(
                label=label,
                label_suffix='',
                required=False) 
Example #30
Source File: plugin.py    From ontask_b with MIT License 5 votes vote down vote up
def _create_datatype_field(p_type, p_help, lbl):
        """Create a new field depending on the datatype."""
        if p_type == 'integer':
            new_field = forms.IntegerField(
                label=lbl,
                required=False,
                help_text=p_help)

        elif p_type == 'double':
            new_field = forms.FloatField(
                label=lbl,
                required=False,
                help_text=p_help)

        elif p_type == 'string':
            new_field = forms.CharField(
                max_length=STRING_PARAM_MAX_LENGTH,
                strip=True,
                required=False,
                label=lbl,
                help_text=p_help)
        elif p_type == 'boolean':
            new_field = forms.BooleanField(
                required=False,
                label=lbl,
                help_text=p_help)
        else:  # p_type == 'datetime':
            new_field = forms.DateTimeField(
                required=False,
                label=lbl,
                widget=DateTimePickerInput(options=DATE_TIME_WIDGET_OPTIONS),
                help_text=p_help)

        return new_field