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

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


当前回答

像Pro一样扩展Django用户模型(UserProfile)

我发现这个非常有用:link

摘录:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)

>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department

其他回答

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

自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

像Pro一样扩展Django用户模型(UserProfile)

我发现这个非常有用:link

摘录:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)

>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department

试试这个:

创建一个名为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)

在这里,我试图解释如何用额外的字段来扩展Django的Default用户模型 很简单,就这么做。

Django允许使用AbstractUser扩展默认的用户模型

注意:-首先创建一个额外的字段模型,你想添加到用户模型,然后运行命令python manage.py makemigrations和python manage.py migrate

首先运行——> python manage.py makemigrationthen

第二步运行python manage.py migrate

步骤:-创建一个带有额外字段的模型,你想在Django默认用户模型中添加这些字段(在我的例子中,我创建了CustomUser

model.py

from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.


class CustomUser(AbstractUser):
    mobile_no = models.IntegerField(blank=True,null=True)
    date_of_birth = models.DateField(blank=True,null=True)

在settings.py中添加你创建的模型名称,在我的例子中CustomUser是用户模型。在settings .py中注册,使其成为默认用户模型,

#settings.py

AUTH_USER_MODEL = 'myapp.CustomUser'

最后在admin.py中注册CustomUser模型 # admin.py

@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
    list_display = ("username","first_name","last_name","email","date_of_birth", "mobile_no")

然后执行命令python manage.py makemigrations

然后python manage.py migrate

然后python manage.py createsuperuser

现在你可以看到你的模型默认用户模型扩展了(mobile_no,date_of_birth)