简体   繁体   English

"在 Django (django-rest-framework) 中创建超级用户时出现致命错误"

[英]Fatal error while creating superuser in Django (django-rest-framework)

I want to make an AbstractUser without a username field so I got this:我想制作一个没有用户名字段的 AbstractUser 所以我得到了这个:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=254, unique=True)
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    session_token = models.CharField(max_length=10, default=0)

    #Newsletter/Shipment Info (not required)
    newsletter = models.BooleanField(default=False)

    first_name = models.CharField(max_length=35, blank=True, null=True)
    last_name = models.CharField(max_length=35, blank=True, null=True)
    adress = models.CharField(max_length=50, blank=True, null=True)
    city = models.CharField(max_length=50, blank=True, null=True)
    postal_code = models.CharField(max_length=6, blank=True, null=True)
    phone = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{9}$/')], blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

You have to inherit from AbstractBaseUser<\/code> not from AbstractUser<\/code> and add Manager Class<\/code> to it您必须从AbstractBaseUser<\/code>而不是从AbstractUser<\/code>继承并向其添加Manager Class<\/code>

class CustomUser(AbstractBaseUser):
    email = models.EmailField(max_length=255, unique=True)
    is_active = models.BooleanField(default=True)
    # Add other fields here

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []


class UserManager(BaseUserManager):
    
    def _create_user(self, email, password, **extra_fields):
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)        
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, **extra_fields)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM