Code

Ticket #7753: 7753.nullboolean.diff

File 7753.nullboolean.diff, 2.0 KB (added by julien, 6 years ago)

Same patch with, hopefully, stronger tests

Line 
1Index: django/django/forms/fields.py
2===================================================================
3--- django/django/forms/fields.py       (revision 8580)
4+++ django/django/forms/fields.py       (working copy)
5@@ -594,7 +594,18 @@
6     widget = NullBooleanSelect
7 
8     def clean(self, value):
9-        return {True: True, False: False}.get(value, None)
10+        """
11+        Explicitly checks for the string 'True' and 'False', which is what a
12+        hidden field will submit for True and False. Unlike the
13+        Booleanfield we also need to check for True, because we are not using
14+        the bool() function
15+        """
16+        if value in (True, 'True'):
17+            return True
18+        elif value in (False, 'False'):
19+            return False
20+        else:
21+            return None
22 
23 class ChoiceField(Field):
24     widget = Select
25Index: django/tests/regressiontests/forms/fields.py
26===================================================================
27--- django/tests/regressiontests/forms/fields.py        (revision 8580)
28+++ django/tests/regressiontests/forms/fields.py        (working copy)
29@@ -1091,6 +1091,20 @@
30 >>> f.clean('3')
31 >>> f.clean('hello')
32 
33+# Make sure that the internal value is preserved if using HiddenInput (#7753)
34+>>> class HiddenNullBooleanForm(Form):
35+...     hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
36+...     hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
37+>>> f = HiddenNullBooleanForm()
38+>>> print f
39+<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />
40+>>> f = HiddenNullBooleanForm({ 'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False' })
41+>>> f.full_clean()
42+>>> f.cleaned_data['hidden_nullbool1']
43+True
44+>>> f.cleaned_data['hidden_nullbool2']
45+False
46+
47 # MultipleChoiceField #########################################################
48 
49 >>> f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])