Django:如何使用自定义字段创建超级用户?

zynd9foi  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(133)

我有一个自定义的User模型在我的models.py和自定义的UserManager以及。我的自定义User模型有username字段,名称更改为login,相同的更新在UserManager以及。一切正常,但是当我尝试使用命令python manage.py createsuperuser创建超级用户时,它要求login,但它没有要求email,最后给了我这个错误:

TypeError: UserManager.create_superuser() missing 1 required positional argument: 'email'

字符串
我的自定义User模型是:

class User(AbstractBaseUser, PermissionsMixin):
    login = models.CharField(max_length=254, unique=True)
    email = models.EmailField(max_length=254, unique=True)
    first_name = models.CharField(max_length=254, null=True, blank=True)
    last_name = models.CharField(max_length=254, null=True, blank=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    
    USERNAME_FIELD = 'login'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)


我的自定义UserManager是:

class UserManager(BaseUserManager):
    def _create_user(self, login, email, password, is_staff, is_admin, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')

        now = timezone.now()
        email = self.normalize_email(email)

        user = self.model(
            login=login,
            email=email,
            is_staff=is_staff,
            is_active=True,
            is_admin=is_admin,
            last_login=now,
            date_joined=now, 
            **extra_fields
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_user(self, login, email, password, **extra_fields):
        user = self._create_user(login, email, password, False, False, **extra_fields)
        user.save(using=self._db)
        
        return user

    def create_superuser(self, login, email, password, **extra_fields):
        user=self._create_user(login, email, password, True, True, **extra_fields)

        return user


admin.py中,我有:

class UserAdmin(BaseUserAdmin):
    fieldsets = (
        (None, {'fields': ('login', 'email', 'password', 'first_name', 'last_name', 'last_login')}),
        ('Permissions', {'fields': (
            'is_active', 
            'is_staff', 
            'is_admin',
            'groups', 
            'user_permissions',
        )}),
    )
    add_fieldsets = (
        (
            None,
            {
                'classes': ('wide',),
                'fields': ('login', 'email', 'password1', 'password2')
            }
        ),
    )

    list_display = ('login', 'email', 'first_name', 'last_name', 'is_admin', 'last_login')
    list_filter = ('is_staff', 'is_admin', 'is_active', 'groups')
    search_fields = ('email', 'login',)
    ordering = ('email', 'login',)
    filter_horizontal = ('groups', 'user_permissions',)

ldfqzlk8

ldfqzlk81#

我只需要在User模型定义的REQUIRED_FIELDS变量中添加'email'。即
我不得不改变以下行:

REQUIRED_FIELDS = []

字符串

REQUIRED_FIELDS = ['email']

zd287kbt

zd287kbt2#

你需要在你的应用程序中创建一个新表单,然后将其引用到你的admin.py模块中。
forms.py

from django import forms

class SignUpForm(forms.ModelForm):
    email = forms.EmailField(...)
    """ other fields ... """

字符串
然后进入您的admin.py

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

class UserAdmin(BaseUserAdmin):
    add_form = SignUpForm # Set your custom form whatever it is

    """ Now go to the base class(built-in UserAdmin) there's a bunch of
    other fields which you can set. you have to override the add_fieldsets
    and include the custom fields you added in your form also to show up 
    these fields you have to override fieldsets as well """

相关问题