使用电子邮件和密码登录 django 站点时出现 30 个字符限制错误
我添加了一个自定义后端,允许用户除了密码之外还可以使用用户名或电子邮件登录。除非电子邮件长度超过 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
我不确定我在哪里我在这里出了问题,我感谢您的帮助。
I have added a custom backend to allow a user to log in with a username or email in addition to password. It works fine except when the email is longer than 30 characters. The form error I get is:
"Ensure this value has at most 30 characters (it has 35)."
In one my my apps' urls.py file I've overridden the max_length of the username field like this:
from django.contrib.auth.forms import AuthenticationForm
AuthenticationForm.base_fields['username'].max_length = 75
I've even tried the class_prepared signal technique described here:
http://stackoverflow.com/questions/2610088/can-djangos-auth-user-username-be-varchar75-how-could-that-be-done/2613385#2613385
I'm not sure where I'm going wrong here and I appreciate the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的目标是简单地更改表单的用户名字段的长度(而不是更改数据库中用户名字段的长度),那么正确的解决方案是像这样子类化 AuthenticationForm:
事实上, AuthenticationForm 的文档字符串甚至说“用于验证用户身份的基类。扩展它以获得接受用户名/密码登录的表单。”
在模板、视图等中使用新表单代替旧的 AuthenticationForm。
至于为什么您的代码不起作用,我的猜测是您的应用程序的 urls.py 在 AuthenticationForm 被导入到其他地方之前没有被加载。我不能发誓这就是原因,但这是最有可能的。
If your aim is to simply alter the length of the username field for the form (and not to alter the length of the username field in the database), then the correct solution is to subclass AuthenticationForm like so:
In fact, the docstring for AuthenticationForm even says "Base class for authenticating users. Extend this to get a form that accepts username/password logins."
Use your new form in place of the old AuthenticationForm in your templates, views, etc.
As for why your code isn't working, my guess is that your app's urls.py isn't being loaded before the AuthenticationForm is being imported elsewhere. I couldn't swear to that being the reason, but it's the most likely.
我的猜测:在 urls.py 上使用:
, login),而不是“惰性求值”形式:
My guess: on urls.py use:
, login),instead of the "lazy evaluation" form:
最好的方法是将此代码添加到顶层 init 中:
但是,如果您选择上面的@Gabriel Hurley 答案,您可以使用以下代码将其传递到登录表单:
Best way is this code added to the top level init:
However, if you choose to us @Gabriel Hurley answer above, you can pass it to the login form by using the following code: