Extending the User model with custom fields in Django

后端 未结 13 1447
别那么骄傲
别那么骄傲 2020-11-21 23:28

What\'s the best way to extend the User model (bundled with Django\'s authentication app) with custom fields? I would also possibly like to use the email as the username (fo

13条回答
  •  星月不相逢
    2020-11-22 00:14

    This is what i do and it's in my opinion simplest way to do this. define an object manager for your new customized model then define your model.

    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
    

    Dont forget to add this line of code in your settings.py:

    AUTH_USER_MODEL = 'YourApp.User'
    

    This is what i do and it always works.

提交回复
热议问题