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

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


当前回答

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

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的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)

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

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

注意:这个答案是不赞成的。如果你使用的是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寻找解决方案的人的。

models.py:

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


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    extra_Field_1 = models.CharField(max_length=25, blank=True)
    extra_Field_2 = models.CharField(max_length=25, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

你可以在这样的模板中使用它:

<h2>{{ user.get_full_name }}</h2>
<ul>
  <li>Username: {{ user.username }}</li>
  <li>Location: {{ user.profile.extra_Field_1 }}</li>
  <li>Birth Date: {{ user.profile.extra_Field_2 }}</li>
</ul>

在views.py中是这样的:

def update_profile(request, user_id):
    user = User.objects.get(pk=user_id)
    user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
    user.save()

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

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'

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