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

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


当前回答

目前在Django 2.2中,当开始一个新项目时,推荐的方法是创建一个自定义的用户模型,它继承自AbstractUser,然后将AUTH_USER_MODEL指向该模型。

来源:https://docs.djangoproject.com/en/2.2/topics/auth/customizing/ using-a-custom-user-model-when-starting-a-project

其他回答

试试这个:

创建一个名为Profile的模型,并使用OneToOneField引用用户,并提供一个related_name选项。

models.py

from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
        if created:
            Profile.objects.create(user=instance).save()
    except Exception as err:
        print('Error creating user profile!')

现在要使用User对象直接访问配置文件,可以使用related_name。

views.py

from django.http import HttpResponse

def home(request):
    profile = f'profile of {request.user.user_profile}'
    return HttpResponse(profile)

自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

这就是我所做的,在我看来这是最简单的方法。为您的新定制模型定义对象管理器,然后定义您的模型。

from django.db import models
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager

class User_manager(BaseUserManager):
    def create_user(self, username, email, gender, nickname, password):
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, gender=gender, nickname=nickname)
        user.set_password(password)
        user.save(using=self.db)
        return user

    def create_superuser(self, username, email, gender, password, nickname=None):
        user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)
        user.is_superuser = True
        user.is_staff = True
        user.save()
        return user



  class User(PermissionsMixin, AbstractBaseUser):
    username = models.CharField(max_length=32, unique=True, )
    email = models.EmailField(max_length=32)
    gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
    gender = models.CharField(choices=gender_choices, default="M", max_length=1)
    nickname = models.CharField(max_length=32, blank=True, null=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    REQUIRED_FIELDS = ["email", "gender"]
    USERNAME_FIELD = "username"
    objects = User_manager()

    def __str__(self):
        return self.username

不要忘记在你的settings.py中添加这行代码:

AUTH_USER_MODEL = 'YourApp.User'

我就是这么做的,而且总是管用。

从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()

目前在Django 2.2中,当开始一个新项目时,推荐的方法是创建一个自定义的用户模型,它继承自AbstractUser,然后将AUTH_USER_MODEL指向该模型。

来源:https://docs.djangoproject.com/en/2.2/topics/auth/customizing/ using-a-custom-user-model-when-starting-a-project