Skip to content

Commit 4a8b8b6

Browse files
Merge pull request derek-schaefer#12 from robthehall/master
Allow an empty value on an optional formfield
2 parents debc404 + d619db6 commit 4a8b8b6

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

json_field/forms.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ def clean(self, value):
1616
# Have to jump through a few hoops to make this reliable
1717
value = super(JSONFormField, self).clean(value)
1818

19+
# allow an empty value on an optional field
20+
if value is None:
21+
return value
22+
1923
## Got to get rid of newlines for validation to work
2024
# Data newlines are escaped so this is safe
2125
value = value.replace('\r', '').replace('\n', '')

test_project/app/forms.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,6 @@
44

55
class TestForm(Form):
66
json = JSONFormField()
7+
8+
class OptionalForm(Form):
9+
json = JSONFormField(required=False)

test_project/app/tests.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from test_project.app.models import Test
2-
from test_project.app.forms import TestForm
2+
from test_project.app.forms import TestForm, OptionalForm
33

44
from django.test import TestCase
55
from django.db.utils import IntegrityError
@@ -107,3 +107,8 @@ def test_formfield(self):
107107
f1 = TestForm(data)
108108
self.assertTrue(f1.is_valid())
109109
self.assertEqual(f1.cleaned_data, data)
110+
f2 = TestForm({})
111+
self.assertFalse(f2.is_valid())
112+
f3 = OptionalForm({})
113+
self.assertTrue(f3.is_valid())
114+
self.assertEqual(f3.cleaned_data, {'json': None})

0 commit comments

Comments
 (0)