在Django中扩展User模型的最佳方式是什么?
17 个回答
自从2008年过去了一段时间,现在是时候给出一个新的答案了。从Django 1.5开始,你可以创建自定义的用户类。实际上,在我写这段话的时候,这个功能已经合并到主版本中,所以你可以试试看。
关于这个功能,你可以在文档中找到一些信息,如果你想更深入了解,可以查看这个提交记录。
你需要做的就是在设置中添加AUTH_USER_MODEL
,并指定自定义用户类的路径,这个类可以扩展AbstractBaseUser
(更灵活的版本)或者AbstractUser
(基本上是你可以扩展的旧用户类)。
对于那些懒得点击的人,这里有个代码示例(摘自文档):
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
u = self.create_user(username,
password=password,
date_of_birth=date_of_birth
)
u.is_admin = True
u.save(using=self._db)
return u
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
注意:这个回答已经过时。如果你使用的是Django 1.7或更高版本,请查看其他回答。
这是我处理的方式。
#in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
#in settings.py
AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'
每次保存用户时,如果用户资料被创建,就会自动生成一个用户资料。
然后你可以使用
user.get_profile().whatever
这里有一些来自文档的更多信息
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
更新:请注意,AUTH_PROFILE_MODULE
从1.5版本开始已经不推荐使用了:https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module
最简单、也是Django推荐的做法是通过一个 OneToOneField(User)
属性来实现。
扩展现有的用户模型
…
如果你想存储与
User
相关的信息,可以使用一个一对一关系,来连接一个包含额外信息字段的模型。这个一对一的模型通常被称为个人资料模型,因为它可能存储与网站用户相关的非认证信息。
不过,扩展 django.contrib.auth.models.User
并替代它也是可以的……
替换自定义用户模型
有些项目可能有认证需求,而Django内置的
User
模型并不总是合适的。例如,在某些网站上,使用电子邮件地址作为身份标识符比使用用户名更合理。[编辑:接下来有两个警告和一个通知,提到这相当激进。]
我建议你不要去修改Django源代码中的实际用户类,或者复制和更改认证模块。