django - 使用电子邮件和密码登录 django 站点时出现 30 个字符限制错误

标签 django django-authentication

我添加了一个自定义后端以允许用户使用用户名或电子邮件以及密码登录。它工作正常,除非电子邮件超过 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/

相关文章:

Django auth - 添加用户字段 - 在管理员中显示

django - 扩展 `auth.models.User` 和用户登录、注销

python - Django : Adding a property to the User class. 在运行时更改它和 UserManager.create_user

python - Django 模型 : user ID

django - from_db_value() 采用 4 个位置参数,但 Django 给出了 5 个

django social-registration 重定向 url 有时/social/setup 和有时/accounts/profile 。为什么?

python - 仅当需要更新时才更新 django 模型中的字段

python - 使用 Django 和 Steam 后端实现 python-social-auth 的正确方法

python - 将 static() 添加到 urlpatterns 只能通过附加到列表来工作

python - 如何将 24 小时军事格式时间存储到 TimeField 中的 Django 模型