Python django.forms.BooleanField() Examples

The following are 30 code examples for showing how to use django.forms.BooleanField(). 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: heltour   Author: cyanfish   File: forms.py    License: MIT License 6 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
Project: fermentrack   Author: thorrak   File: forms.py    License: 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 3
Project: starthinker   Author: google   File: forms_json.py    License: 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 4
Project: zing   Author: evernote   File: forms.py    License: 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 5
Project: zentral   Author: zentralopensource   File: forms.py    License: 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 6
Project: django-ca   Author: mathiasertl   File: fields.py    License: 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 7
Project: firefox-profilemaker   Author: allo-   File: forms.py    License: 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 8
Project: TWLight   Author: WikipediaLibrary   File: tests.py    License: 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 9
Project: helfertool   Author: helfertool   File: subscribe.py    License: 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 10
Project: coursys   Author: sfu-fas   File: markup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, with_wysiwyg=False, rows=20, default_markup='creole', allow_math=True, restricted=False,
                 max_length=100000, required=True, *args, **kwargs):
        choices = MARKUP_CHOICES_WYSIWYG if with_wysiwyg else MARKUP_CHOICES
        fields = [
            forms.CharField(required=required, max_length=max_length),
            forms.ChoiceField(choices=choices, required=True),
            forms.BooleanField(required=False),
        ]
        self.required = required
        self.force_display_required = required

        help_url = '/docs/markup' # hard-coded URL because lazy-evaluating them is hard
        default_help = '<a href="' + help_url + '">Markup language</a> used in the content'
        if allow_math:
            default_help += ', and should <a href="http://www.mathjax.org/">MathJax</a> be used for displaying TeX formulas?'
        default_help += ' <span id="markup-help"></span>'
        help_text = kwargs.pop('help_text', mark_safe(default_help))

        super(MarkupContentField, self).__init__(fields, required=False,
            help_text=help_text,
            *args, **kwargs)

        self.fields[0].required = required
        self.widget.widgets[0].attrs['rows'] = rows
        self.fields[1].required = required
        self.widget.widgets[1].choices = choices

        self.widget.allow_math = allow_math
        self.restricted = restricted
        self.widget.default_markup = default_markup 
Example 11
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, is_team_league, round_to_close, round_to_open, season_to_close, *args,
                 **kwargs):
        super(RoundTransitionForm, self).__init__(*args, **kwargs)

        if round_to_close is not None:
            self.fields['complete_round'] = forms.BooleanField(initial=True,
                                                               required=False,
                                                               label='Set round %d as completed' % round_to_close.number)
            self.fields['round_to_close'] = forms.IntegerField(initial=round_to_close.number,
                                                               widget=forms.HiddenInput)

        if season_to_close is not None:
            self.fields['complete_season'] = forms.BooleanField(initial=True,
                                                                required=False,
                                                                label='Set %s as completed' % season_to_close.name)

        if round_to_open is not None:
            if is_team_league:
                self.fields['update_board_order'] = forms.BooleanField(initial=True,
                                                                       required=False,
                                                                       label='Update board order')
            self.fields['generate_pairings'] = forms.BooleanField(initial=True,
                                                                  required=False,
                                                                  label='Generate pairings for round %d' % round_to_open.number)
            self.fields['round_to_open'] = forms.IntegerField(initial=round_to_open.number,
                                                              widget=forms.HiddenInput) 
Example 12
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['blank'] = True
        super(BooleanField, self).__init__(*args, **kwargs) 
Example 13
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 14
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 15
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "BooleanField" 
Example 16
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 17
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 = 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 18
Project: wagtail-tag-manager   Author: jberghoef   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for tag_type, config in TagTypeSettings.all().items():
            value = config.get("value")
            initial = value == SETTING_INITIAL or value == SETTING_REQUIRED

            if SETTING_INITIAL in kwargs:
                initial = kwargs.get(SETTING_INITIAL)[tag_type]

            self.fields[tag_type] = forms.BooleanField(
                label=config.get("verbose_name"),
                required=value == SETTING_REQUIRED,
                disabled=value == SETTING_REQUIRED,
                initial=initial,
            ) 
Example 19
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "BooleanField" 
Example 20
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 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().formfield(**defaults) 
Example 21
Project: tom_base   Author: TOMToolkit   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def extra_field_to_form_field(field_type):
    if field_type == 'number':
        return forms.FloatField(required=False)
    elif field_type == 'boolean':
        return forms.BooleanField(required=False)
    elif field_type == 'datetime':
        return forms.DateTimeField(required=False)
    elif field_type == 'string':
        return forms.CharField(required=False, widget=forms.Textarea)
    else:
        raise ValueError(
            'Invalid field type {}. Field type must be one of: number, boolean, datetime string'.format(field_type)
        ) 
Example 22
Project: zulip   Author: zulip   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args: Any, **kwargs: Any) -> None:
        # Since the superclass doesn't except random extra kwargs, we
        # remove it from the kwargs dict before initializing.
        self.realm_creation = kwargs['realm_creation']
        del kwargs['realm_creation']

        super().__init__(*args, **kwargs)
        if settings.TERMS_OF_SERVICE:
            self.fields['terms'] = forms.BooleanField(required=True)
        self.fields['realm_name'] = forms.CharField(
            max_length=Realm.MAX_REALM_NAME_LENGTH,
            required=self.realm_creation) 
Example 23
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if settings.USE_REMEMBER_ME:
            self.fields['remember_me'] = forms.BooleanField(label=_('Remember me'), required=False) 
Example 24
Project: rdmo   Author: rdmorganiser   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)

        # add a consent field, the label is added in the template
        if settings.ACCOUNT_TERMS_OF_USE:
            self.fields['consent'] = forms.BooleanField(required=True) 
Example 25
Project: byro   Author: byro   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, member=None, **kwargs):
        initial = kwargs.pop("initial", {})
        initial[
            "is_visible_to_members"
        ] = member.profile_memberpage.is_visible_to_members
        super().__init__(*args, initial=initial, **kwargs)
        self.member = member

        blocked = [
            "sepa",
            "secret",
            "balance",
            "active",
            "_internal_id",
            "memberpage",
            "memberships.last",
        ]

        for key, value in member.get_fields().items():
            if (
                any(b in value.path for b in blocked)
                or any(key in b for b in blocked)
                or key == "pk"
            ):
                continue
            self.fields[key] = forms.BooleanField(
                required=False,
                label=value.name,
                initial=self.member.profile_memberpage.publication_consent.get(
                    "fields", {}
                )
                .get(key, {})
                .get("visibility"),
            ) 
Example 26
Project: cadasta-platform   Author: Cadasta   File: test_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_init_with_widget(self):
        resource = ResourceFactory.build()
        field = ResourceField(resource=resource, widget=BooleanField())

        assert isinstance(field.widget, BooleanField)
        assert field.resource == resource 
Example 27
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):
        super(SettingsForm, self).__init__(*args, **kwargs)
        if 'instance' in kwargs:
            press = kwargs['instance']
            settings = press_models.PressSetting.objects.filter(press=press)

            for setting in settings:
                if setting.is_boolean:
                    self.fields[setting.name] = forms.BooleanField(widget=forms.CheckboxInput(), required=False)
                else:
                    self.fields[setting.name] = forms.CharField(widget=forms.TextInput(), required=False)
                self.fields[setting.name].initial = setting.value 
Example 28
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 29
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 30
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "BooleanField"