Here are the examples of the python api django.forms.BooleanField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
34 Examples
3
View Complete Implementation : __init__.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
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_clast': forms.BooleanField}
defaults.update(kwargs)
return super(BooleanField, self).formfield(**defaults)
3
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : chrisjrn
Copyright Apache License 2.0
Author : chrisjrn
@clastmethod
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
3
View Complete Implementation : forms.py
Copyright MIT License
Author : cyanfish
Copyright MIT License
Author : cyanfish
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)
3
View Complete Implementation : forms.py
Copyright MIT License
Author : DjangoPatternsBook
Copyright MIT License
Author : DjangoPatternsBook
def __init__(self, *args, **kwargs):
vip = kwargs.pop("vip", False)
super().__init__(*args, **kwargs)
# Are you a VIP?
if vip:
self.fields["first_clast"] = forms.BooleanField(
label="Fly First Clast?",
required=False,
initial=True,
help_text="First-clast only offered to VIPs")
self.helper = FormHelper(self)
self.helper.layout.append(Submit('submit', 'Submit'))
3
View Complete Implementation : common_tags.py
Copyright GNU General Public License v2.0
Author : getway
Copyright GNU General Public License v2.0
Author : getway
@register.filter
def is_bool_field(field):
if isinstance(field, forms.BooleanField):
return True
else:
return False
3
View Complete Implementation : present.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
def __init__(self, *args, **kwargs):
self.shift = kwargs.pop('shift')
super(PresentForm, self).__init__(*args, **kwargs)
for helper in self.shift.helper_set.all():
id_str = "helper_{}".format(helper.pk)
self.fields[id_str] = forms.BooleanField(
label=_(helper.full_name),
required=False,
initial=helper.gifts.get_present(self.shift))
3
View Complete Implementation : subscribe.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
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},
)
3
View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jberghoef
Copyright BSD 3-Clause "New" or "Revised" License
Author : jberghoef
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,
)
3
View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
def comment_form_factory(with_complaints=False, complaint_label=None):
if not with_complaints:
return CommentForm
else:
return type(
'ComplaintForm',
(CommentForm,),
dict(
complaint=forms.BooleanField(
required=False,
label=complaint_label,
),
base_fields='text complaint tamper'.split()
)
)
3
View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
Copyright MIT License
Author : labd
def test_checkbox_field(self):
data = self.get_form_field_data('checkbox')
cls = wsf_fields.CheckboxField()
field = cls.get_formfield(data)
self.astertIsInstance(field, forms.BooleanField)
self.astertIsInstance(field.widget, forms.widgets.CheckboxInput)
self.astertEqual(field.label, data['label'])
self.astertEqual(field.required, data['required'])
self.astertEqual(field.help_text, data['help_text'])
3
View Complete Implementation : test_booleanfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_booleanfield_clean_1(self):
f = BooleanField()
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.astertTrue(f.clean(True))
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(False)
self.astertTrue(f.clean(1))
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(0)
self.astertTrue(f.clean('Django rocks'))
self.astertTrue(f.clean('True'))
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('False')
3
View Complete Implementation : test_booleanfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_booleanfield_clean_2(self):
f = BooleanField(required=False)
self.astertIs(f.clean(''), False)
self.astertIs(f.clean(None), False)
self.astertIs(f.clean(True), True)
self.astertIs(f.clean(False), False)
self.astertIs(f.clean(1), True)
self.astertIs(f.clean(0), False)
self.astertIs(f.clean('1'), True)
self.astertIs(f.clean('0'), False)
self.astertIs(f.clean('Django rocks'), True)
self.astertIs(f.clean('False'), False)
self.astertIs(f.clean('false'), False)
self.astertIs(f.clean('FaLsE'), False)
3
View Complete Implementation : test_booleanfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_booleanfield_changed(self):
f = BooleanField()
self.astertFalse(f.has_changed(None, None))
self.astertFalse(f.has_changed(None, ''))
self.astertFalse(f.has_changed('', None))
self.astertFalse(f.has_changed('', ''))
self.astertTrue(f.has_changed(False, 'on'))
self.astertFalse(f.has_changed(True, 'on'))
self.astertTrue(f.has_changed(True, ''))
# Initial value may have mutated to a string due to show_hidden_initial (#19537)
self.astertTrue(f.has_changed('False', 'on'))
# HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict
self.astertFalse(f.has_changed(False, 'False'))
self.astertFalse(f.has_changed(True, 'True'))
self.astertTrue(f.has_changed(False, 'True'))
self.astertTrue(f.has_changed(True, 'False'))
3
View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_booleanfield(self):
e = {
'required': 'REQUIRED',
}
f = BooleanField(error_messages=e)
self.astertFormErrors(['REQUIRED'], f.clean, '')
3
View Complete Implementation : forms.py
Copyright MIT License
Author : NicolasLM
Copyright MIT License
Author : NicolasLM
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
tos_page = reverse_lazy('django.contrib.flatpages.views.flatpage',
kwargs={'url': '/terms-of-service'})
label = mark_safe(_('I have read and I agree with the <a href="%s">'
'Terms of Service</a>') % tos_page)
self.fields['tos'] = forms.BooleanField(required=True, label=label)
3
View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
Copyright Apache License 2.0
Author : ooknosi
def test_MaterialForm_materializes_BooleanField(self):
"""django.forms.widgets.CheckboxInput should be converted to
material_widgets.widgets.MaterialCheckboxInput.
"""
clast CheckboxInputForm(MaterialForm):
checkbox_input = forms.BooleanField()
form = CheckboxInputForm()
self.astertEqual(
type(form.fields['checkbox_input'].widget),
widgets.MaterialCheckboxInput,
)
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_field_boolean(self):
field = BooleanField()
context = Context({"field": field})
self.TEMPLATE.render(context)
template_path = "wiki/forms/fields/boolean.html"
context = {"field": field, "is_markitup": False, "render_labels": True}
wiki_extra.render.astert_called_with(template_path, context)
3
View Complete Implementation : forms.py
Copyright MIT License
Author : wise-team
Copyright MIT License
Author : wise-team
def __init__(self, *args, **kwargs):
self.base_fields[self.SERVICE_TYPE_FORM] = CharField(widget=HiddenInput)
self.base_fields[self.NOTIFY_FORM] = BooleanField(label="""
Notify about new items added to timeline by this set of rules, by posting following comment bellow posts:
""", required=False)
kwargs.setdefault('label_suffix', '')
super(TimelineManagementForm, self).__init__(*args, **kwargs)
0
View Complete Implementation : select.py
Copyright MIT License
Author : abelardopardo
Copyright MIT License
Author : abelardopardo
def __init__(self, *args, **kargs):
"""Initialize the fields for the given columns.
Kargs contain:
column_names: list with names of the columns to upload,
is_key: list stating if the corresponding column is key
:param args:
:param kargs: Multiple additional parameters to store.
"""
# Names of the columns to process and Boolean stating if they are key
self.column_names = kargs.pop('column_names')
self.columns_to_upload = kargs.pop('columns_to_upload')
self.is_key = kargs.pop('is_key')
self.keep_key = kargs.pop('keep_key')
super().__init__(*args, **kargs)
# Create as many fields as the given columns
col_info = zip(self.column_names, self.columns_to_upload)
for idx, (colname, upload) in enumerate(col_info):
self.fields['upload_%s' % idx] = forms.BooleanField(
initial=upload,
label='',
required=False)
self.fields['new_name_%s' % idx] = forms.CharField(
initial=colname,
label='',
strip=True,
required=False)
# Field to confirm if the key columns are kept.
if self.is_key[idx]:
self.fields['make_key_%s' % idx] = forms.BooleanField(
initial=self.keep_key[idx],
label='',
required=False)
0
View Complete Implementation : workflow.py
Copyright MIT License
Author : abelardopardo
Copyright MIT License
Author : abelardopardo
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)
0
View Complete Implementation : fields.py
Copyright MIT License
Author : Arx-Game
Copyright MIT License
Author : Arx-Game
def webform_field(self, caller=None):
options = {'label': self.full_name, 'required': False}
return django.forms.BooleanField(**options)
0
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
Copyright Apache License 2.0
Author : c3nav
def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs):
self.request = request
super().__init__(*args, **kwargs)
creating = not self.instance.pk
if hasattr(self.instance, 'author_id'):
if self.instance.author_id is None:
self.instance.author = request.user
if 'geometry' in self.fields:
if not geometry_editable:
# can't see this geometry in editor
self.fields.pop('geometry')
else:
# hide geometry widget
self.fields['geometry'].widget = HiddenInput()
if not creating:
self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':'))
if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser:
Source = self.request.changeset.wrap_model('Source')
sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id',
'left', 'bottom', 'right', 'top')}
used_names = set(sources.keys())
all_names = set(os.listdir(settings.SOURCES_ROOT))
if not creating:
used_names.remove(self.instance.name)
all_names.add(self.instance.name)
self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names)))
if creating:
for s in sources.values():
s['access_restriction'] = s['access_restriction_id']
del s['access_restriction_id']
self.fields['copy_from'] = ChoiceField(
choices=tuple((('', '---------'), ))+tuple(
(json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name)
for name in sorted(used_names)
),
required=False
)
self.fields['fixed_x'] = DecimalField(label='fixed x', required=False,
max_digits=7, decimal_places=3, initial=0)
self.fields['fixed_y'] = DecimalField(label='fixed y', required=False,
max_digits=7, decimal_places=3, initial=0)
self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False,
max_digits=7, decimal_places=3, initial=1)
self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False,
max_digits=7, decimal_places=3, initial=1)
self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True)
self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True)
self.fields.move_to_end('lock_scale', last=False)
self.fields.move_to_end('lock_aspect', last=False)
self.fields.move_to_end('scale_y', last=False)
self.fields.move_to_end('scale_x', last=False)
self.fields.move_to_end('fixed_y', last=False)
self.fields.move_to_end('fixed_x', last=False)
self.fields.move_to_end('access_restriction', last=False)
if creating:
self.fields.move_to_end('copy_from', last=False)
self.fields.move_to_end('name', last=False)
if self._meta.model.__name__ == 'AccessRestriction':
AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup')
self.fields['groups'].label_from_instance = lambda obj: obj.satle
self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request)
elif 'groups' in self.fields:
LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory')
kwargs = {'allow_'+self._meta.model._meta.default_related_name: True}
categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups')
if self.instance.pk:
instance_groups = tuple(self.instance.groups.values_list('pk', flat=True))
else:
instance_groups = ()
self.fields.pop('groups')
for category in categories:
choices = tuple((str(group.pk), group.satle)
for group in sorted(category.groups.all(), key=self.sort_group))
category_groups = set(group.pk for group in category.groups.all())
initial = tuple(str(pk) for pk in instance_groups if pk in category_groups)
if category.single:
name = 'group_'+category.name
initial = initial[0] if initial else ''
choices = (('', '---'), )+choices
field = ChoiceField(label=category.satle, required=False, initial=initial, choices=choices,
help_text=category.help_text)
else:
name = 'groups_'+category.name
field = MultipleChoiceField(label=category.satle_plural, required=False,
initial=initial, choices=choices,
help_text=category.help_text)
self.fields[name] = field
if 'label_settings' in self.fields:
self.fields.move_to_end('label_settings')
for field in tuple(self.fields.keys()):
if field.startswith('label_override'):
self.fields.move_to_end(field)
if 'category' in self.fields:
self.fields['category'].label_from_instance = attrgetter('satle')
if 'label_settings' in self.fields:
self.fields['label_settings'].label_from_instance = attrgetter('satle')
if 'access_restriction' in self.fields:
AccessRestriction = self.request.changeset.wrap_model('AccessRestriction')
self.fields['access_restriction'].label_from_instance = lambda obj: obj.satle
self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request)
if 'base_mapdata_accessible' in self.fields:
if not request.user.is_superuser:
self.fields['base_mapdata_accessible'].disabled = True
if space_id and 'target_space' in self.fields:
Space = self.request.changeset.wrap_model('Space')
GraphNode = self.request.changeset.wrap_model('GraphNode')
GraphEdge = self.request.changeset.wrap_model('GraphEdge')
cache_key = 'editor:neighbor_spaces:%s:%s%d' % (
self.request.changeset.raw_cache_key_by_changes,
AccessPermission.cache_key_for_request(request, with_update=False),
space_id
)
other_spaces = cache.get(cache_key, None)
if other_spaces is None:
AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0)
space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True))
space_edges = GraphEdge.objects.filter(
Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes)
).values_list('from_node_id', 'to_node_id')
other_nodes = set(chain(*space_edges)) - space_nodes
other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True))
other_spaces.discard(space_id)
cache.set(cache_key, other_spaces, 900)
for space_field in ('origin_space', 'target_space'):
other_space_id = getattr(self.instance, space_field+'_id', None)
if other_space_id:
other_spaces.add(other_space_id)
space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces)
for space_field in ('origin_space', 'target_space'):
if space_field in self.fields:
self.fields[space_field].label_from_instance = lambda obj: obj.satle
self.fields[space_field].queryset = space_qs
self.redirect_slugs = None
self.add_redirect_slugs = None
self.remove_redirect_slugs = None
if 'slug' in self.fields:
self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True))
self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma seperated)'), required=False,
initial=','.join(self.redirect_slugs))
self.fields.move_to_end('redirect_slugs', last=False)
self.fields.move_to_end('slug', last=False)
if 'from_node' in self.fields:
self.fields['from_node'].widget = HiddenInput()
if 'to_node' in self.fields:
self.fields['to_node'].widget = HiddenInput()
if 'data' in self.fields and 'data' in self.initial:
self.initial['data'] = json.dumps(self.initial['data'])
self.is_json = is_json
self.missing_fields = tuple((name, field) for name, field in self.fields.items()
if name not in self.data and not field.required)
0
View Complete Implementation : forms.py
Copyright MIT License
Author : cyanfish
Copyright MIT License
Author : cyanfish
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)
0
View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
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)
0
View Complete Implementation : converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
@convert_form_field.register(forms.BooleanField)
def convert_form_field_to_boolean(field):
return Boolean(description=field.help_text, required=field.required)
0
View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
def test_should_boolean_convert_boolean():
field = astert_conversion(forms.BooleanField, Boolean)
astert isinstance(field.type, NonNull)
0
View Complete Implementation : account.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
def __init__(self, *args, **kwargs):
self._admin_user = kwargs.pop("admin_user")
super(EditUserForm, self).__init__(*args, **kwargs)
# set required fields
for f in ("first_name", "last_name", "email"):
self.fields[f].required = True
# adjust labels of active and superuser flags
self._active_initial = self.instance.is_active
if _user_flag_changeable(self.instance, "is_active"):
self.fields["is_active"].help_text = ""
else:
self.fields["is_active"].help_text = _("Managed by LDAP group")
self.fields["is_active"].disabled = True
self._superuser_initial = self.instance.is_superuser
self.fields["is_superuser"].label = _("Administrator")
if _user_flag_changeable(self.instance, "is_superuser"):
self.fields["is_superuser"].help_text = ""
else:
self.fields["is_superuser"].help_text = _("Managed by LDAP group")
self.fields["is_superuser"].disabled = True
# permission: adduser
self._adduser_initial = has_adduser_group(self.instance)
self.fields["perm_adduser"] = forms.BooleanField(
label=_("Add users"),
required=False,
initial=self._adduser_initial,
)
# permission: addevent
self._addevent_initial = has_addevent_group(self.instance)
self.fields["perm_addevent"] = forms.BooleanField(
label=_("Add events"),
required=False,
initial=self._addevent_initial,
)
# permission: sendnews
self._sendnews_initial = has_sendnews_group(self.instance)
self.fields["perm_sendnews"] = forms.BooleanField(
label=_("Send newsletter"),
required=False,
initial=self._sendnews_initial,
)
0
View Complete Implementation : helpersgifts.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
def __init__(self, *args, **kwargs):
super(HelpersGiftsForm, self).__init__(*args, **kwargs)
if not self.instance.helper.event.ask_shirt:
self.fields.pop('got_shirt')
self.fields.pop('buy_shirt')
for giftset in self.instance.deservedgiftset_set.all():
delivered_id_str = "delivered_{}".format(giftset.pk)
self.fields[delivered_id_str] = forms.BooleanField(
label=_("Delivered"),
required=False,
initial=giftset.delivered)
for shift in self.instance.helper.shifts.all():
present_id_str = "present_{}".format(shift.pk)
self.fields[present_id_str] = forms.BooleanField(
label=_("Present"),
required=False,
initial=self.instance.get_present(shift))
0
View Complete Implementation : registration.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
def __init__(self, *args, **kwargs):
""" Customize the form.
The fields 'shirt' and 'vegetarian' are removed, if they are not
necessary. Then the custom fields for the shifts are created.
"""
self.event = kwargs.pop('event')
self.displayed_shifts = kwargs.pop('shifts')
self.selected_shifts = kwargs.pop('selected_shifts', [])
self.internal = kwargs.pop('internal', False)
self.link = kwargs.pop('link', False)
self.shifts = {}
super(RegisterForm, self).__init__(*args, **kwargs)
# remove field for phone number
if not self.event.ask_phone:
self.fields.pop('phone')
# remove field for shirt?
if not self.event.ask_shirt:
self.fields.pop('shirt')
else:
self.fields['shirt'].choices = self.event.get_shirt_choices(
internal=self.internal)
# remove field for vegetarian food?
if not self.event.ask_vegetarian:
self.fields.pop('vegetarian')
# remove field or privacy statement?
if self.internal:
self.fields.pop('privacy_statement')
else:
# add link to show privacy statement after label
privacy_label = format_html(
'{} (<a href="" data-toggle="collapse" data-target="#privacy">{}</a>)',
self.fields['privacy_statement'].label,
_("Show"),
)
self.fields['privacy_statement'].label = privacy_label
# add field for age?
self.ask_full_age = self.event.ask_full_age and not self.internal
if self.ask_full_age:
self.fields['full_age'] = forms.BooleanField(
label=_("I confirm to be full aged."), required=False)
# add field for notification about new events
self.ask_news = self.event.ask_news and not self.internal
if self.ask_news:
news_label = format_html(
'{} (<a href="" data-toggle="collapse" data-target="#privacy_newsletter">{}</a>)',
_("I want to be informed about future events that are looking for helpers."),
_("show privacy statement"),
)
self.fields['news'] = forms.BooleanField(label=news_label, required=False)
# get a list of all shifts
if self.displayed_shifts:
all_shifts = self.displayed_shifts
else:
all_shifts = Shift.objects.filter(job__event=self.event,
hidden=False)
# add fields for shifts
for shift in all_shifts:
id = 'shift_%s' % shift.pk
self.fields[id] = forms.BooleanField(label=shift,
required=False)
# disable button if shift is full
if shift.is_full() or (shift.blocked and not
self.displayed_shifts):
self.fields[id].widget.attrs['disabled'] = True
# check button if this shift should be selected
if shift in self.selected_shifts:
self.fields[id].widget.attrs['checked'] = True
# set clast if infection instruction is needed for this shift
if shift.job.infection_instruction:
self.fields[id].widget.attrs['clast'] = 'infection_instruction'
self.fields[id].widget.attrs['onClick'] = \
'handle_infection_instruction()'
# safe mapping id <-> pk
self.shifts[id] = shift.pk
0
View Complete Implementation : config_forms.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def __init__(self, field_items, skip_check=False, *args, **kwargs):
self.field_dict = OrderedDict(field_items)
self.skip_check = skip_check
# Make sure no subfield is named 'SKIP_CHECK_NAME'. If
# skip_check is True this field will clash with the addtional
# subfield added by the DictCharField constructor. We perform
# this check even if skip_check=False because having a field named
# 'skip_check' that isn't used to actually skip the checks would be
# very confusing.
if SKIP_CHECK_NAME in self.field_dict:
raise RuntimeError(
"'%s' is a reserved name "
"(it can't be used to name a subfield)." % SKIP_CHECK_NAME
)
# if skip_check: add a BooleanField to the list of fields, this will
# be used to skip the validation of the fields and accept arbitrary
# data.
if skip_check:
self.field_dict[SKIP_CHECK_NAME] = forms.BooleanField(
required=False
)
self.names = [name for name in self.field_dict]
# Create the DictCharWidget with init values from the list of fields.
self.fields = list(self.field_dict.values())
self.widget = DictCharWidget(
[field.widget for field in self.fields],
self.names,
[field.initial for field in self.fields],
[field.label for field in self.fields],
skip_check=skip_check,
)
# Upcall to Field and not MultiValueField to avoid setting all the
# subfields' 'required' attributes to False.
Field.__init__(self, *args, **kwargs)
0
View Complete Implementation : pods.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
if self.request is None:
raise ValueError("'request' kwargs is required.")
self.pod = kwargs.pop("pod", None)
if self.pod is None:
raise ValueError("'pod' kwargs is required.")
super(ComposeMachineForm, self).__init__(*args, **kwargs)
# Build the fields based on the pod and current pod hints.
self.fields["cores"] = IntegerField(
min_value=1, max_value=self.pod.hints.cores, required=False
)
self.initial["cores"] = 1
self.fields["memory"] = IntegerField(
min_value=1024, max_value=self.pod.hints.memory, required=False
)
self.initial["memory"] = 1024
self.fields["architecture"] = ChoiceField(
choices=[(arch, arch) for arch in self.pod.architectures],
required=False,
)
self.initial["architecture"] = self.pod.architectures[0]
if self.pod.hints.cpu_speed > 0:
self.fields["cpu_speed"] = IntegerField(
min_value=300,
max_value=self.pod.hints.cpu_speed,
required=False,
)
else:
self.fields["cpu_speed"] = IntegerField(
min_value=300, required=False
)
def duplicated_hostname(hostname):
if Node.objects.filter(hostname=hostname).exists():
raise ValidationError(
'Node with hostname "%s" already exists' % hostname
)
self.fields["hostname"] = CharField(
required=False, validators=[duplicated_hostname, validate_hostname]
)
self.initial["hostname"] = make_unique_hostname()
self.fields["domain"] = ModelChoiceField(
required=False, queryset=Domain.objects.all()
)
self.initial["domain"] = Domain.objects.get_default_domain()
self.fields["zone"] = ModelChoiceField(
required=False, queryset=Zone.objects.all()
)
self.initial["zone"] = Zone.objects.get_default_zone()
self.fields["pool"] = ModelChoiceField(
required=False, queryset=ResourcePool.objects.all()
)
self.initial["pool"] = self.pod.pool
self.fields["storage"] = CharField(
validators=[storage_validator], required=False
)
self.initial["storage"] = "root:8(local)"
self.fields["interfaces"] = LabeledConstraintMapField(
validators=[interfaces_validator],
label="Interface constraints",
required=False,
)
self.initial["interfaces"] = None
self.fields["skip_commissioning"] = BooleanField(required=False)
self.initial["skip_commissioning"] = False
self.allocated_ips = {}
0
View Complete Implementation : test_booleanfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_boolean_picklable(self):
self.astertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField)
0
View Complete Implementation : test_booleanfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_disabled_has_changed(self):
f = BooleanField(disabled=True)
self.astertIs(f.has_changed('True', 'False'), False)
0
View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : tetraly
Copyright GNU General Public License v3.0
Author : tetraly
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for flag in FLAGS:
self.fields[flag[0]] = forms.BooleanField(required=False, initial=False)