Can I change the USERNAME_FIELD in Django 1.5 without creating a custom user?

删除回忆录丶 提交于 2019-11-30 16:55:31

问题


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.

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

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.

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?


回答1:


#Your app's __init__.py

from django.contrib.auth.models import User

User.USERNAME_FIELD = 'email'



回答2:


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

Declare your email as the USERNAME_FIELD there

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



来源:https://stackoverflow.com/questions/15668124/can-i-change-the-username-field-in-django-1-5-without-creating-a-custom-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!