Django 无法识别 forms.Form 子项上的关键字空白

Django doesn't recognise keyword blank on child of forms.Form

我正在尝试创建一个表单,该表单将在其某些值中接收空字符串。此表单不受模型对象支持。我这样定义它:

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)

除非我尝试运行 测试:

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())

我得到以下异常:

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'

根据文档,这应该没问题。我错过了什么吗?

不,文档没有提到表单字段的 blank 参数;那是针对模型字段的。

表单字段采用默认为 True 的 required parameter

这是因为 Django 表单字段不接受 blank 参数。

Django表单域接受的core parameters有:

  • 需要

  • 标签

  • label_suffix

  • 初始

  • 小部件

  • help_text

  • error_messages

  • 验证者

  • 本地化

    您可以改为传递值为 Falserequired 参数。因此,如果您传递一个空值 – None 或空字符串 "",表单将不会引发验证错误。