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
- [Answer]-Python django class based view and functional view
- [Answer]-Django: Using same object how to show 2 different results in django template?
- [Answer]-Django many-to-many lookup from different models
- [Answer]-Django ModelChoiceField to_field_name is not working
Source:stackexchange.com