diff --git a/django_filters/widgets.py b/django_filters/widgets.py index c0796e40e..77501169c 100644 --- a/django_filters/widgets.py +++ b/django_filters/widgets.py @@ -97,3 +97,23 @@ def decompress(self, value): if value is None: return [None, None] return value + + +class BooleanWidget(forms.Widget): + """Convert true/false values into the internal Python True/False. + This can be used for AJAX queries that pass true/false from JavaScript's + internal types through. + """ + def value_from_datadict(self, data, files, name): + """ + """ + value = super(BooleanWidget, self).value_from_datadict( + data, files, name) + + if value is not None: + if value.lower() == 'true': + value = True + elif value.lower() == 'false': + value = False + + return value diff --git a/docs/ref/widgets.txt b/docs/ref/widgets.txt index 177efcee0..7acd017d0 100644 --- a/docs/ref/widgets.txt +++ b/docs/ref/widgets.txt @@ -8,12 +8,21 @@ arguments. ~~~~~~~~~~~~~~ This widget renders each option as a link, instead of an actual . It has -one method that you can overide for additional customizability. +one method that you can override for additional customizability. ``option_string()`` should return a string with 3 Python keyword argument placeholders:: 1. ``attrs``: This is a string with all the attributes that will be on the final ```` tag. 2. ``query_string``: This is the query string for use in the ``href`` - option on the ```` elemeent. + option on the ```` element. 3. ``label``: This is the text to be displayed to the user. + +``BooleanWidget`` +~~~~~~~~~~~~~~~~~ + +This widget converts its input into Python's True/False values. It will convert +all case variations of ``True`` and ``False`` into the internal Python values. +To use it, pass this into the ``widgets`` argument of the ``BooleanFilter``:: + + active = BooleanFilter(widget=BooleanWidget()) diff --git a/tests/test_widgets.py b/tests/test_widgets.py index 9bc1114fe..ab7fd9ab8 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -4,6 +4,7 @@ from django.test import TestCase from django.forms import TextInput, Select +from django_filters.widgets import BooleanWidget from django_filters.widgets import RangeWidget from django_filters.widgets import LinkWidget from django_filters.widgets import LookupTypeWidget @@ -135,3 +136,22 @@ def test_widget(self): - """) + +class BooleanWidgetTests(TestCase): + """ + """ + def test_widget_value_from_datadict(self): + """ + """ + w = BooleanWidget() + + trueActive = {'active': 'true'} + result = w.value_from_datadict(trueActive, {}, 'active') + self.assertEqual(result, True) + + falseActive = {'active': 'false'} + result = w.value_from_datadict(falseActive, {}, 'active') + self.assertEqual(result, False) + + result = w.value_from_datadict({}, {}, 'active') + self.assertEqual(result, None)