Django注册Redux:如何将唯一标识符从用户名更改为电子邮件,并使用电子邮件作为登录名 [英] Django Registration Redux: how to change the unique identifier from username to email and use email as login

查看:168
本文介绍了Django注册Redux:如何将唯一标识符从用户名更改为电子邮件,并使用电子邮件作为登录名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Django-registration-redux进行用户注册。它使用使用用户名作为唯一标识符的默认用户模型。

现在我们要丢弃用户名,并使用电子邮件作为唯一标识符。

我们还要使用电子邮件而不是使用电子邮件用户名登录
如何实现这个?

可以不改变 AUTH_USER_MODEL 设置吗?

I'm using Django-registration-redux in my project for user registration. It uses default User model which use username as the unique identifier.
Now we want to discard username and use email as the unique identifier.
And also we want to use email instead of username to login. How to achieve this?
And is it possible to do it without changing the AUTH_USER_MODEL settings?

因为从官方的文档它说如果您打算设置AUTH_USER_MODEL,您应该首先在创建任何迁移或运行manage.py 迁移之前将其设置为

Because from the official doc it says"If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time."

推荐答案

您可以覆盖此类注册表单

You can override registration form like this

from registration.forms import RegistrationForm
class MyRegForm(RegistrationForm):
    username = forms.CharField(max_length=254, required=False, widget=forms.HiddenInput())

    def clean_email(self):
        email = self.cleaned_data['email']
        self.cleaned_data['username'] = email
        return email

然后将其添加到设置文件(阅读这个链接

And then add this to settings file (read this link for details)

REGISTRATION_FORM = 'app.forms.MyRegForm'

这将把电子邮件设置为用户名字段,然后一切都可以正常工作,因为电子邮件现在是用户名。

This will set the email to username field as well and then everything will work as email is now the username.

唯一的问题是用户名字段在DB中的最大长度为30。因此,超过30个字符的电子邮件会引发DB异常。要解决这个覆盖用户模型(请参阅详细信息)。

The only problem is that username field has a max lenght of 30 in DB. So emails longer than 30 chars will raise DB exception. To solve that override the user model (read this for details).

这篇关于Django注册Redux:如何将唯一标识符从用户名更改为电子邮件,并使用电子邮件作为登录名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆