Python django.forms.CheckboxInput() Examples
The following are 30
code examples of django.forms.CheckboxInput().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_checkboxinput.py From djongo with GNU Affero General Public License v3.0 | 7 votes |
def test_render_check_test(self): """ You can pass 'check_test' to the constructor. This is a callable that takes the value and returns True if the box should be checked. """ widget = CheckboxInput(check_test=lambda value: value.startswith('hello')) self.check_html(widget, 'greeting', '', html=( '<input type="checkbox" name="greeting">' )) self.check_html(widget, 'greeting', 'hello', html=( '<input checked type="checkbox" name="greeting" value="hello">' )) self.check_html(widget, 'greeting', 'hello there', html=( '<input checked type="checkbox" name="greeting" value="hello there">' )) self.check_html(widget, 'greeting', 'hello & goodbye', html=( '<input checked type="checkbox" name="greeting" value="hello & goodbye">' ))
Example #2
Source File: markup.py From coursys with GNU General Public License v3.0 | 6 votes |
def __init__(self): widgets = ( forms.Textarea(attrs={'cols': 70, 'rows': 20}), forms.Select(), forms.CheckboxInput(), ) super(MarkupContentWidget, self).__init__(widgets)
Example #3
Source File: forms.py From peering-manager with Apache License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) custom_widgets = [forms.CheckboxInput, forms.RadioSelect] for field_name, field in self.fields.items(): if field.widget.__class__ in custom_widgets: css = field.widget.attrs.get("class", "") field.widget.attrs["class"] = " ".join( [css, "custom-control-input"] ).strip() else: css = field.widget.attrs.get("class", "") field.widget.attrs["class"] = " ".join([css, "form-control"]).strip() if field.required: field.widget.attrs["required"] = "required" if "placeholder" not in field.widget.attrs: field.widget.attrs["placeholder"] = field.label
Example #4
Source File: forms.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def __init__(self, *args, **kwargs): key_type = kwargs.pop('key_type', None) value = kwargs.pop('value', None) super(EditKey, self).__init__(*args, **kwargs) if key_type == 'rich-text': self.fields['value'].widget = SummernoteWidget() elif key_type == 'boolean': self.fields['value'].widget = forms.CheckboxInput() elif key_type == 'integer': self.fields['value'].widget = forms.TextInput(attrs={'type': 'number'}) elif key_type == 'file' or key_type == 'journalthumb': self.fields['value'].widget = forms.FileInput() elif key_type == 'text': self.fields['value'].widget = forms.Textarea() else: self.fields['value'].widget.attrs['size'] = '100%' self.fields['value'].initial = value self.fields['value'].required = False
Example #5
Source File: fields.py From hypha with BSD 3-Clause "New" or "Revised" License | 6 votes |
def value_from_datadict(self, data, files, name): if hasattr(files, 'getlist'): upload = files.getlist(name) else: upload = files.get(name) if not isinstance(upload, list): upload = [upload] checkbox_name = self.clear_checkbox_name(name) + '-' checkboxes = {k for k in data if checkbox_name in k} cleared = { int(checkbox.replace(checkbox_name, '')) for checkbox in checkboxes if CheckboxInput().value_from_datadict(data, files, checkbox) } return { 'files': upload, 'cleared': cleared, }
Example #6
Source File: test_checkboxinput.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_render_check_exception(self): """ Calling check_test() shouldn't swallow exceptions (#17888). """ widget = CheckboxInput( check_test=lambda value: value.startswith('hello'), ) with self.assertRaises(AttributeError): widget.render('greeting', True)
Example #7
Source File: bootstrap.py From OpenMDM with Apache License 2.0 | 5 votes |
def is_checkbox(field): return isinstance(field.field.widget, forms.CheckboxInput)
Example #8
Source File: helpers.py From python2017 with MIT License | 5 votes |
def __init__(self, form, field, is_first): self.field = form[field] # A django.forms.BoundField instance self.is_first = is_first # Whether this field is first on the line self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) self.is_readonly = False
Example #9
Source File: widgets.py From imoocc with GNU General Public License v2.0 | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs if DJANGO_11: final_attrs = self.build_attrs(attrs, extra_attrs={'name': name}) else: final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #10
Source File: widgets.py From devops with MIT License | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_str(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_str(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_str(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #11
Source File: widgets.py From online with GNU Affero General Public License v3.0 | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs if DJANGO_11: final_attrs = self.build_attrs(attrs, extra_attrs={'name': name}) else: final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #12
Source File: form_as_div.py From ctf-gameserver with ISC License | 5 votes |
def _get_css_classes(field): """ Helper function which returns the appropriate (Bootstrap) CSS classes for rendering an input field and its `<div>` container. Returns: A tuple of the form `(div_classes, field_classes, iterate_subfields, wrap_in_label)`. `iterate_subfields` is a bool indicating that the field should be rendered by iterating over its sub-fields (i.e. over itself) and wrapping them in containers with `field_classes`. This is required for multiple radios and checkboxes belonging together. `wrap_in_label` is a bool that specifies whether the input field should be placed inside the associated `<label>`, as required by Bootstrap for checkboxes. """ div_classes = [] field_classes = [] iterate_subfields = False wrap_in_label = False if field.errors: div_classes.append('has-error') widget = field.field.widget if isinstance(widget, CheckboxInput): div_classes.append('checkbox') wrap_in_label = True elif isinstance(widget, CheckboxSelectMultiple): div_classes.append('form-group') field_classes.append('checkbox') iterate_subfields = True elif isinstance(widget, RadioSelect): div_classes.append('form-group') field_classes.append('radio') iterate_subfields = True elif isinstance(widget, FileInput): pass elif isinstance(widget, MultiWidget): div_classes.append('form-group') div_classes.append('form-inline') field_classes.append('form-control') else: div_classes.append('form-group') field_classes.append('form-control') return (div_classes, field_classes, iterate_subfields, wrap_in_label)
Example #13
Source File: widgets.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs if DJANGO_11: final_attrs = self.build_attrs(attrs, extra_attrs={'name': name}) else: final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #14
Source File: views.py From TWLight with MIT License | 5 votes |
def get_form_class(self): """ Dynamically construct a form which will have a checkbox for every partner. """ fields = {} field_order = [] open_apps = Application.objects.filter( editor=self.request.user.editor, status__in=( Application.SENT, Application.QUESTION, Application.PENDING, Application.APPROVED, ), ) open_apps_partners = [] for i in open_apps: open_apps_partners.append(i.partner.company_name) for partner in Partner.objects.filter( ~Q(authorization_method=Partner.BUNDLE) ).order_by("company_name"): # We cannot just use the partner ID as the field name; Django won't # be able to find the resultant data. # http://stackoverflow.com/a/8289048 if partner.company_name not in open_apps_partners: field_name = "partner_{id}".format(id=partner.id) fields[field_name] = forms.BooleanField( label=partner.company_name, required=False, # We need to pass the partner to the front end in order to # render the partner information tiles. Widget attrs appear to # be the place we can stash arbitrary metadata. Ugh. widget=forms.CheckboxInput(attrs={"object": partner}), ) field_order.append(partner.company_name) form_class = type("RfAForm", (forms.Form,), fields) form_class.field_order = field_order return form_class
Example #15
Source File: forms.py From TWLight with MIT License | 5 votes |
def __init__(self, *args, **kwargs): self._validate_parameters(**kwargs) self.field_params = kwargs.pop("field_params") try: self.user = kwargs.pop("requested_user") except KeyError: pass super(BaseApplicationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self._initialize_form_helper() self.helper.layout = Layout() user_data = self.field_params.pop("user") self._add_user_data_subform(user_data) # For each partner, build a partner data section of the form. for partner in self.field_params: self._add_partner_data_subform(partner) # Make sure to align any checkbox inputs with other field types self.helper.filter_by_widget(forms.CheckboxInput).wrap( Div, css_class="col-sm-8 col-sm-offset-4 col-md-9 col-md-offset-3 apply-tos" ) self.helper.add_input( Submit( "submit", # Translators: Labels the button users click to apply for a partner's resources. _("Apply"), css_class="center-block", ) )
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('active',) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field('active').get_default(), True)
Example #17
Source File: widgets.py From Mxonline3 with Apache License 2.0 | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, extra_attrs={'name': name}) output = [] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #18
Source File: test_checkboxinput.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_value_from_datadict(self): """ The CheckboxInput widget will return False if the key is not found in the data dictionary (because HTML form submission doesn't send any result for unchecked checkboxes). """ self.assertFalse(self.widget.value_from_datadict({}, {}, 'testing'))
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('active',) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field('active').get_default(), True)
Example #20
Source File: test_checkboxinput.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_render_check_exception(self): """ Calling check_test() shouldn't swallow exceptions (#17888). """ widget = CheckboxInput( check_test=lambda value: value.startswith('hello'), ) with self.assertRaises(AttributeError): widget.render('greeting', True)
Example #21
Source File: test_checkboxinput.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_value_from_datadict(self): """ The CheckboxInput widget will return False if the key is not found in the data dictionary (because HTML form submission doesn't send any result for unchecked checkboxes). """ self.assertFalse(self.widget.value_from_datadict({}, {}, 'testing'))
Example #22
Source File: cas_server.py From django-cas-server with GNU General Public License v3.0 | 5 votes |
def is_checkbox(field): """ check if a form bound field is a checkbox :param django.forms.BoundField field: A bound field :return: ``True`` if the field is a checkbox, ``False`` otherwise. :rtype: bool """ return isinstance(field.field.widget, forms.CheckboxInput)
Example #23
Source File: widgets.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #24
Source File: base.py From avos with Apache License 2.0 | 5 votes |
def get_data(self, datum, column, row): """Fetches the data to be displayed in this cell.""" table = row.table if column.auto == "multi_select": data = "" if row.can_be_selected(datum): widget = forms.CheckboxInput(check_test=lambda value: False) # Convert value to string to avoid accidental type conversion data = widget.render('object_ids', unicode(table.get_object_id(datum)), {'class': 'table-row-multi-select'}) table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "form_field": widget = column.form_field if issubclass(widget.__class__, forms.Field): widget = widget.widget widget_name = "%s__%s" % \ (column.name, unicode(table.get_object_id(datum))) # Create local copy of attributes, so it don't change column # class form_field_attributes form_field_attributes = {} form_field_attributes.update(column.form_field_attributes) # Adding id of the input so it pairs with label correctly form_field_attributes['id'] = widget_name data = widget.render(widget_name, column.get_data(datum), form_field_attributes) table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "actions": data = table.render_row_actions(datum, pull_right=False) table._data_cache[column][table.get_object_id(datum)] = data else: data = column.get_data(datum) if column.cell_attributes_getter: cell_attributes = column.cell_attributes_getter(data) or {} self.attrs.update(cell_attributes) return data
Example #25
Source File: __init__.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def value_from_datadict(self, data, files, name): if name not in data: return True else: return super(CheckboxInput, self).value_from_datadict( data, files, name )
Example #26
Source File: forms.py From django-is-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_checkbox(field): return (hasattr(field, 'field') and hasattr(field.field, 'widget') and (isinstance(field.field.widget, CheckboxInput) or (isinstance(field.field.widget, WrapperWidget) and isinstance(field.field.widget.widget, CheckboxInput))))
Example #27
Source File: djangocms_forms_tags.py From djangocms-forms with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_checkbox(field): return isinstance(field.field.widget, forms.CheckboxInput)
Example #28
Source File: forms.py From djangocms-forms with BSD 3-Clause "New" or "Revised" License | 5 votes |
def prepare_checkbox(self, field): field_attrs = field.build_field_attrs() widget_attrs = field.build_widget_attrs() field_attrs.update({ 'widget': forms.CheckboxInput(attrs=widget_attrs) }) if field.initial: field_attrs.update({ 'initial': self.to_bool(field.initial) }) return forms.BooleanField(**field_attrs)
Example #29
Source File: widgets.py From CTF_AWD_Platform with MIT License | 5 votes |
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, extra_attrs={'name': name}) output = [] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
Example #30
Source File: file.py From coursys with GNU General Public License v3.0 | 5 votes |
def value_from_datadict(self, data, files, name): # override to accept the case "clear + file upload" without ValidationError upload = super().value_from_datadict(data, files, name) if not self.is_required and forms.CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): #if upload: # return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload