Python django.forms.CheckboxInput() Examples

The following are 30 code examples for showing how to use django.forms.CheckboxInput(). 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: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 6 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        name = str(name)
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '%(input)s'
        substitutions['input'] = super(forms.ClearableFileInput, self).render(name, value, attrs, renderer=renderer)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = ('<a href="%s">%s</a>'
                                        % (escape(value.file_sub.get_file_url()),
                                           escape(value.file_sub.display_filename())))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = escape(checkbox_name)
                substitutions['clear_checkbox_id'] = escape(checkbox_id)
                substitutions['clear'] = forms.CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions) 
Example 2
Project: peering-manager   Author: respawner   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 4
Project: hypha   Author: OpenTechFund   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 5
Project: djongo   Author: nesdis   File: test_checkboxinput.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 &amp; goodbye">'
        )) 
Example 6
Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: Apache License 2.0 5 votes vote down vote up
def is_checkbox(field):
    return isinstance(field.field.widget, forms.CheckboxInput) 
Example 7
Project: coursys   Author: sfu-fas   File: file.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 8
Project: coursys   Author: sfu-fas   File: markup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        widgets = (
            forms.Textarea(attrs={'cols': 70, 'rows': 20}),
            forms.Select(),
            forms.CheckboxInput(),
        )
        super(MarkupContentWidget, self).__init__(widgets) 
Example 9
Project: StormOnline   Author: stormsha   File: widgets.py    License: Apache License 2.0 5 votes vote down vote up
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
Project: GTDWeb   Author: lanbing510   File: helpers.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 11
Project: djangoSIGE   Author: thiagopena   File: custom_tags.py    License: MIT License 5 votes vote down vote up
def is_checkbox(field):
    return field.field.widget.__class__.__name__ == CheckboxInput().__class__.__name__ 
Example 12
Project: bioforum   Author: reBiocoder   File: helpers.py    License: MIT License 5 votes vote down vote up
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 13
Project: waliki   Author: mgaitan   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean(self):
        cleaned_data = super(MovePageForm, self).clean()
        slug = cleaned_data['slug']
        just_redirect = cleaned_data.get('just_redirect', False)
        if self.instance.slug == slug:
            raise forms.ValidationError(_("The slug wasn't changed"))

        if Page.objects.filter(slug=slug).exists() and not just_redirect:
            self.fields['just_redirect'].widget = forms.CheckboxInput()
            raise forms.ValidationError(_("There is already a page with this slug"))

        return cleaned_data 
Example 14
Project: waliki   Author: mgaitan   File: test_views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_post_error_if_target_already_exist(self):
        new_page = PageFactory(raw="hello test!", slug='target-page')
        response = self.client.post(self.move_url, {'slug': 'target-page'})
        self.assertEqual(response.status_code, 200)
        form = response.context[0]['form']
        self.assertEqual(form.errors, {'__all__': ["There is already a page with this slug"]})
        self.assertIsInstance(form.fields['just_redirect'].widget, forms.CheckboxInput) 
Example 15
Project: django-users2   Author: mishbahr   File: form_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_checkbox(field):
    return isinstance(field.field.widget, forms.CheckboxInput) 
Example 16
Project: weibo-analysis-system   Author: Superbsco   File: widgets.py    License: MIT License 5 votes vote down vote up
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 17
Project: InvenTree   Author: inventree   File: views.py    License: MIT License 5 votes vote down vote up
def get_form(self):
        form = super(AjaxCreateView, self).get_form()

        # Force display of the 'deep_copy' widget
        form.fields['deep_copy'].widget = CheckboxInput()

        return form 
Example 18
Project: myblog   Author: myminwang   File: widgets.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 19
Project: CTF_AWD_Platform   Author: xuchaoa   File: widgets.py    License: MIT License 5 votes vote down vote up
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 20
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 21
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 22
Project: django_OA   Author: abaoMAO   File: widgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 23
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: helpers.py    License: MIT License 5 votes vote down vote up
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 24
Project: python   Author: Yeah-Kun   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
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 25
Project: openhgsenti   Author: drexly   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
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 26
Project: eventoL   Author: eventoL   File: filters.py    License: GNU General Public License v3.0 5 votes vote down vote up
def is_checkbox(boundfield):
    """Return True if this field's widget is a CheckboxInput."""
    widget = boundfield.field.widget
    is_checkbox_input = isinstance(widget, forms.CheckboxInput)
    is_checkbox_select = isinstance(widget, forms.CheckboxSelectMultiple)
    return is_checkbox_input or is_checkbox_select 
Example 27
Project: eventoL   Author: eventoL   File: test_templatetag_filters.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_is_checkbox_with_CheckboxInput_return_true(mocker):
    boundfield = mocker.Mock()
    boundfield.field = mocker.Mock()
    boundfield.field.widget = forms.CheckboxInput()
    assert filters.is_checkbox(boundfield) 
Example 28
Project: Mxonline3   Author: mtianyan   File: widgets.py    License: Apache License 2.0 5 votes vote down vote up
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 29
Project: python2017   Author: bpgc-cte   File: helpers.py    License: MIT License 5 votes vote down vote up
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 30
Project: imoocc   Author: iopsgroup   File: widgets.py    License: GNU General Public License v2.0 5 votes vote down vote up
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))