用Django中的自定义字段扩展用户模型

使用自定义字段扩展用户模型(与Django的身份验证应用程序捆绑在一起)的最佳方式是什么? 我也可能想使用电子邮件作为用户名(用于验证目的)。

我已经看到了一些方法来做到这一点,但不能决定哪一个是最好的。


Django推荐的最简单的方法是通过OneToOneField(User)属性。

扩展现有的用户模型

...

如果您希望存储与User相关的信息,则可以使用包含字段的模型的一对一关系以获取更多信息。 这种一对一模式通常称为配置文件模型,因为它可能存储有关站点用户的非auth相关信息。

这就是说,扩展django.contrib.auth.models.User并取代它也可以...

替换自定义用户模型

某些类型的项目可能具有身份验证要求,而Django的内置User模型并不总是适合的。 例如,在一些网站上,使用电子邮件地址作为您的身份标记而不是用户名更有意义。

[编辑: 两个警告和通知后面提到这是非常激烈的 。]

我肯定会远离更改Django源代码树中的实际User类和/或复制和更改auth模块。


注意:此答案已弃用。 如果您使用的是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自v1.5 AUTH_PROFILE_MODULE已弃用:https: AUTH_PROFILE_MODULE


那么,自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
链接地址: http://www.djcxy.com/p/33755.html

上一篇: Extending the User model with custom fields in Django

下一篇: how to set dynamic initial values to django modelform field