[Answer]-Django modelform display blank for null

1๐Ÿ‘

By default, each Field class assumes the value is required, so if you pass an empty value โ€“ either None or the empty string ("") โ€“ then clean() will raise a ValidationError exception:

>>> from django import forms
>>> f = forms.CharField()
>>> f.clean('foo')
u'foo'
>>> f.clean('')
Traceback (most recent call last):
...
ValidationError: [u'This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError: [u'This field is required.']

If a Field has required=False and you pass clean() an empty value, then clean() will return a normalized empty value rather than raising ValidationError. For CharField, this will be a Unicode empty string. For other Field classes, it might be None. (This varies from field to field.)

Like this:

>>> f = forms.CharField(required=False)
>>> f.clean('foo')
u'foo'
>>> f.clean('')
u''
>>> f.clean(None)
u''
๐Ÿ‘คStephen Lin

0๐Ÿ‘

Instead I ended up using forms.HiddenInput() and did not display the field with null, which fits my case perfectly well!

๐Ÿ‘คuser956424

Leave a comment