我可以在不创建自定义用户的情况下更改Django 1.5中的USERNAME_FIELD吗?

时间:2021-05-25 19:23:37

I am trying to use the email field in the default Django user model as the username. I am using Django 1.5 and I saw that the default user has a USERNAME_FIELD property.

我试图使用默认Django用户模型中的电子邮件字段作为用户名。我正在使用Django 1.5,我发现默认用户有一个USERNAME_FIELD属性。

In my project, I would like to set the following USERNAME_FIELD = 'email' as a default in the user model.

在我的项目中,我想在用户模型中将以下USERNAME_FIELD ='email'设置为默认值。

This small but fundamental tweak is the only thing I would like to change in the user model. I was wondering if there is a way of changing the USERNAME_FIELD without having to subclass the AbstractUser. I saw in this question that you can subclass the AbstractUser and write a custom manager for it.

这个小但基本的调整是我想在用户模型中改变的唯一方法。我想知道是否有一种方法可以更改USERNAME_FIELD而无需继承AbstractUser。我在这个问题中看到你可以继承AbstractUser并为它编写一个自定义管理器。

So I was wondering if there is a simpler way of changing that property?

所以我想知道是否有更简单的方法来改变这个属性?

And if not, what would be the minimal way of extending the AbstractUser to use the email field as username?

如果没有,扩展AbstractUser以使用电子邮件字段作为用户名的最小方法是什么?

2 个解决方案

#1


4  

#Your app's __init__.py

from django.contrib.auth.models import User

User.USERNAME_FIELD = 'email'

#2


1  

You have to write a new Custom User Class by extending the AbstractBaseUser and not AbstractUser

您必须通过扩展AbstractBaseUser而不是AbstractUser来编写新的自定义用户类

Declare your email as the USERNAME_FIELD there

在那里将您的电子邮件声明为USERNAME_FIELD

Optionally you can also declare a custom user manager that extends from BaseUserManager to handle the username required constraint. You can remove username from that manager's create_user function

(可选)您还可以声明从BaseUserManager扩展的自定义用户管理器,以处理用户名所需的约束。您可以从该经理的create_user函数中删除用户名

#1


4  

#Your app's __init__.py

from django.contrib.auth.models import User

User.USERNAME_FIELD = 'email'

#2


1  

You have to write a new Custom User Class by extending the AbstractBaseUser and not AbstractUser

您必须通过扩展AbstractBaseUser而不是AbstractUser来编写新的自定义用户类

Declare your email as the USERNAME_FIELD there

在那里将您的电子邮件声明为USERNAME_FIELD

Optionally you can also declare a custom user manager that extends from BaseUserManager to handle the username required constraint. You can remove username from that manager's create_user function

(可选)您还可以声明从BaseUserManager扩展的自定义用户管理器,以处理用户名所需的约束。您可以从该经理的create_user函数中删除用户名