Skip to content

Instantly share code, notes, and snippets.

@nitely
Created July 27, 2014 09:18
Show Gist options
  • Select an option

  • Save nitely/39f49aab77a79026dcb7 to your computer and use it in GitHub Desktop.

Select an option

Save nitely/39f49aab77a79026dcb7 to your computer and use it in GitHub Desktop.
Django template filter for checking if a field is a BooleanField (checkbox)
#-*- coding: utf-8 -*-
from django.forms.widgets import CheckboxInput
from .. import register
@register.filter
def is_checkbox(field):
if isinstance(field.field.widget, CheckboxInput):
return True
else:
return False
#-*- coding: utf-8 -*-
from django.test import TestCase
class UtilsTemplateTagTests(TestCase):
def test_is_checkbox(self):
"""
return True if the field is a checkbox
"""
class CheckBoxForm(forms.Form):
checkbox = forms.BooleanField()
nocheckbox = forms.CharField()
out = Template(
"{% load spirit_tags %}"
"{% for field in form.visible_fields %}"
"{{ field|is_checkbox }},"
"{% endfor %}"
).render(Context({'form': CheckBoxForm(), }))
self.assertEqual(out.strip(), "True,False,")
@Coykto
Copy link

Coykto commented Jul 20, 2018

import .. register

is:

from django import template
register = template.Library()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment