Django管理员错误“请更正以下错误”。

时间:2018-12-05 09:07:36

标签: django django-admin django-custom-user django-custom-manager

我已经创建了自定义BaseUserManager来创建用户,但是当我从django管理面板中添加用户时却出现“请更正以下错误”的错误,但我找不到问题所在。

Models.py:

class UserManager(BaseUserManager):

    def create_user(self,email,password):
        user = self.model(email=email)
        user.set_password(password)

    def create_superuser(self,email,password):
        user = self.model(email=email)
        user.set_password(password)
        user.is_admin = True
        user.is_superuser = True
        user.is_staff=True
        user.save(using=self._db)




class User(AbstractBaseUser,PermissionsMixin):

    COMPANY='CO'
    EMPLOYEE='EM'
    STATUS_CHOICES=(
        (COMPANY,'Company'),
        (EMPLOYEE,'Employee'),
    )
    Status=models.CharField(max_length=2,
                            choices=STATUS_CHOICES,
                            default=EMPLOYEE)
    user_image = models.CharField(max_length=100)
    is_admin=models.BooleanField()
    email=models.EmailField(unique=True)
    is_staff=models.BooleanField(default=False)
    object = UserManager()
    USERNAME_FIELD='email'
    REQUIRED_FIELDS = []

    objects=models.Manager()

    def get_short_name(self):
        return self.email

Admin.py文件:

class UserAdmin(UserAdmin):
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)

    fieldsets = (
        (None, {'fields': ('email', 'password','Status','user_image','last_login')}),

        ('Permissions', {'fields': ('is_admin','is_staff','is_superuser','user_permissions','groups')}),
    )

    add_fieldsets= (
        (None, {'fields': ('email', 'password','Status','user_image','last_login')}),

        ('Permissions', {'fields': ('is_admin','is_staff','is_superuser','user_permissions','groups')}),
    )

    search_fields = ('password',)
    ordering = ('password',)
    filter_horizontal = ()



admin.site.register(User,UserAdmin)
admin.site.register(Company)
admin.site.register(Employee)
admin.site.register(Job)
admin.site.register(AppliedJobs)

有人可以建议我做错了吗?从管理面板添加用户时,总是会出现错误。由于我是第一次使用baseusermanager,所以无法弄清楚。

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助。

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Create and save a user with the given email, and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_admin', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_admin', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

您所使用的Manager版本中的方法不会返回任何内容,但是应该返回。

答案 1 :(得分:0)

我可以建议如何尝试并发现问题。通常,您的UserAdmin将引用表单,请参见下文:

class UserAdmin(UserAdmin):
    add_form = SignUpForm
    form = CustomUserChangeForm

您可以通过使用日志记录找出导致错误的原因。将以下Mixin添加到您的SignUpFormCustomUserChangeForm

import logging

logger = logging.getLogger(__name__)


# see https://stackoverflow.com/questions/20833638/how-to-log-all-django-form-validation-errors
class LoggingMixin(object):
    def add_error(self, field, error):
        if field:
            logger.info('Form error on field %s: %s', field, error)
        else:
            logger.info('Form error: %s', error)
        super().add_error(field, error)

# e.g.
class SignUpForm(LoggingMixin, UserCreationForm):
    ....

现在,登录或更改用户,然后检查日志以找出导致“请更正以下错误”的原因。