gpt4 book ai didi

Django 1.10自定义用户 'is_superuser'与模型中的 'is_superuser'字段发生冲突

转载 作者:行者123 更新时间:2023-12-03 17:44:20 43 4
gpt4 key购买 nike

我在CustomUser中编写了一个自定义用户类-models.py,主要是在here之后

import re

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.core import validators
from django.contrib.auth.models import (AbstractUser, PermissionsMixin,
UserManager)


class CustomUser(AbstractUser, PermissionsMixin):
"""
custom user, reference below example
https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[validators.RegexValidator(
re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(_('email address'), max_length=254)
create_time = models.DateTimeField(auto_now_add=True)
active = models.BooleanField() # if we can retrieval it from outside

objects = UserManager()

USERNAME_FIELD = 'username'

class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')

def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])

def __str__(self):
return self.username

然后我在 admin.py中注册了它
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser

# Register your models here.


class CustomUserAdmin(UserAdmin):
model = CustomUser

admin.site.register(CustomUser, CustomUserAdmin)

但是,当我运行 python manage.py createsuperuser创建 super 用户时,出现以下错误:
ERRORS:
myapp.CustomUser.is_superuser: (models.E006) The field 'is_superuser' clash
es with the field 'is_superuser' from model 'myapp.customuser'.

最佳答案

is_superuser字段在PermissionMixin上定义。但是,AbstractUser也是PermissionMixin的子类,因此您实际上是从同一类继承两次。这会导致字段冲突,因为Django的较早版本不允许子类覆盖字段(最新版本允许覆盖抽象基类上定义的字段)。

您要么必须从AbstractBaseUserPermissionMixin继承,要么仅从AbstractUser继承。 AbstractUser定义了一些其他字段,包括usernameis_staffis_active以及其他一些内容。

关于Django 1.10自定义用户 'is_superuser'与模型中的 'is_superuser'字段发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46093946/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com