您真的应该覆盖身份验证表单。该视图接受一个允许您轻松覆盖表单的参数。
我认为这样的事情应该可行:
你需要做的就是像这样覆盖 clean_username 方法:
编辑:
由于form and field validation docs 中的以下原因,覆盖 clean_username 方法无法更改验证错误消息:
字段上的 clean() 方法
子类。这是负责
运行 to_python,验证和
以正确的顺序运行验证器
并传播他们的错误。如果,在
任何时候,任何方法都会引发
ValidationError,验证停止
并引发了该错误。这种方法
返回干净的数据,然后
插入到cleaned_data
形式的字典。
clean_<fieldname>() 方法在
表单子类——在哪里
替换为表单的名称
字段属性。这个方法做任何
特定于那个的清洁
特定属性,与
它是字段的类型。这种方法
没有传递任何参数。你会
需要查找字段的值
在 self.cleaned_data 并记住
这将是一个 Python 对象
点,而不是原始字符串
以表格形式提交(它将在
clean_data 因为通用字段
上面的 clean() 方法已经
清理数据一次)。
首先验证 Field 子类并返回用于clean_<field_name>() 方法的已清理数据。如果发生错误,该字段的验证将停止。
这意味着要覆盖消息,您需要覆盖字段验证或使字段不需要值,因此在该步骤不会引发验证错误并在 clean_<fieldname>() 方法中引发必需的方法
>>> from django.contrib.auth.forms import AuthenticationForm
>>> class MyAuthForm(AuthenticationForm):
... def __init__(self, *args, **kwargs):
... super(MyAuthForm, self).__init__(*args,**kwargs)
... self.fields['username'].error_messages['required']='Custom Required Msg'
...
>>> form = MyAuthForm(data={'password':'asdf'})
>>> form.is_valid()
False
>>> form.errors
{'username': [u'Custom Required Msg']}
>>>
urls.py
from someapp.forms import MyAuthForm
urlpatterns = patterns('',
...
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'someapp/login.html', 'authentication_form':MyAuthForm, }),
...