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

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


当前回答

注意:这个答案是不赞成的。如果你使用的是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起已弃用:https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module

其他回答

关于存储用户的附加信息,有一个官方建议。 Django手册也在Profiles部分讨论了这个问题。

从Django 1.5开始,你可以很容易地扩展用户模型,在数据库中只保留一个表。

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _

class UserProfile(AbstractUser):
    age = models.PositiveIntegerField(_("age"))

您还必须在设置文件中将其配置为当前用户类

# supposing you put it in apps/profiles/models.py
AUTH_USER_MODEL = "profiles.UserProfile"

如果你想添加很多用户的首选项,OneToOneField选项可能是一个更好的选择。

给开发第三方库的人一个提示:如果您需要访问用户类,请记住人们可以更改它。使用官方帮助获取正确的类

from django.contrib.auth import get_user_model

User = get_user_model()

简单而有效的方法是 models.py

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

自2008年以来已经过去了一段时间,是时候给出一些新的答案了。从Django 1.5开始,你将能够创建自定义User类。实际上,在我写这个的时候,它已经合并到master中了,所以你可以试试。

在文档中有一些关于它的信息,如果你想深入了解,在这个提交中。

您所要做的就是将AUTH_USER_MODEL添加到具有自定义用户类路径的设置中,它扩展了AbstractBaseUser(更可定制的版本)或AbstractUser(或多或少可以扩展的旧用户类)。

对于那些懒得点击的人,这里有一个代码示例(摘自docs):

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.5中的新功能,现在你可以创建自己的自定义用户模型(在上述情况下,这似乎是一件好事)。参考“在Django中自定义身份验证”

这可能是1.5版本中最酷的新功能。