我添加了一个自定义后端以允许用户使用用户名或电子邮件以及密码登录。它工作正常,除非电子邮件超过 30 个字符。我得到的表单错误是:
"Ensure this value has at most 30 characters (it has 35)."
在我的应用程序的一个 urls.py 文件中,我像这样覆盖了用户名字段的 max_length:
from django.contrib.auth.forms import AuthenticationForm
AuthenticationForm.base_fields['username'].max_length = 75
我什至尝试过这里描述的 class_prepared 信号技术:
http://stackoverflow.com/questions/2610088/can-djangos-auth-user-username-be-varchar75-how-could-that-be-done/2613385#2613385
我不确定我哪里出错了,非常感谢您的帮助。
最佳答案
如果您的目标是简单地更改表单的用户名字段的长度(而不是更改数据库中用户名字段的长度),那么正确的解决方案是子类化 AuthenticationForm,如下所示:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class MyAuthenticationForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=75)
事实上,AuthenticationForm 的文档字符串甚至说“用于验证用户的基类。扩展它以获得接受用户名/密码登录的表单。”
在模板、 View 等中使用新表单代替旧的 AuthenticationForm。
至于为什么您的代码不起作用,我的猜测是在将 AuthenticationForm 导入其他地方之前,您的应用程序的 urls.py 没有被加载。我不能发誓这就是原因,但这是最有可能的。
关于django - 使用电子邮件和密码登录 django 站点时出现 30 个字符限制错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112005/