I'm trying to create a form that will receive empty strings in some of its values. This form is not backed by a model object. I've defined it thus:
class SearchForm(forms.Form):
device = fields.CharField(blank=True)
min_release_date = fields.CharField(blank=True)
price_range = fields.CharField(blank=True)
has_in_app_purchases = fields.CharField(blank=True)
Except when I try to run a test:
def test_valid_no_data(self):
from webanalytics.web.search import ANY_PRICE, DEFAULT_DATES, HAS_IAP_IDS
form_data = {
'price_range': ANY_PRICE[0],
'min_release_date': DEFAULT_DATES[0],
'has_in_app_purchases': HAS_IAP_IDS[0]
}
search = SearchForm(form_data)
self.assertTrue(search.is_valid())
I get the following exception:
ERROR: Failure: TypeError (__init__() got an unexpected keyword argument 'blank')
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/loader.py", line 411, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python2.7/dist-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python2.7/dist-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/workspace/aa/tests/ci/unit/webanalytics/web/test_forms.py", line 5, in <module>
from webanalytics.forms import SearchForm
File "/workspace/aa/webanalytics/forms.py", line 8, in <module>
class SearchForm(forms.Form):
File "/workspace/aa/webanalytics/forms.py", line 15, in SearchForm
device = fields.CharField(blank=True)
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py", line 187, in __init__
super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'blank'
According to the docs this should be ok. Am I missing something?
This is because Django form fields don't accept a blank
parameter.
The core parameters accepted by Django form fields are:
required
label
label_suffix
initial
widget
help_text
error_messages
validators
localize
You can instead pass a required
parameter with its value as False
. So, if you pass an empty value – either None
or the empty string ""
, the form will not raise a validation error.