Django自定义用户模型无法登录管理页面

标签 django django-models django-admin

我在 Django 中有一个自定义用户模型。当我从命令行创建新的 super 用户时,该用户可以登录管理界面。新的 super 用户以 is_superuser 和 is_staff 为 true 开始。现在,当我从管理界面创建新的自定义用户并将 is_staff 和 is_superuser 设置为 true 时,该新用户无法登录管理界面。

您不需要将 is_staff 设置为 true 即可登录管理界面吗?如果是这样,为什么这对从管理界面创建的用户不起作用?

我是否可以更改决定用户是否可以登录管理界面的因素?如果是这样,怎么办!

我完全困惑了,非常感谢对这个问题的一些见解!提前致谢!

模型.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from django.contrib.auth.models import Group, Permission
import datetime


class MyUserManager(BaseUserManager):
    def _create_user(self, username, password,
                     is_superuser, is_active, is_staff):
        if not username:
            raise ValueError('The given email must be set')
        user = self.model(
            username=username,
            is_active=is_active,
            is_superuser=is_superuser,
            is_staff=is_staff
        )

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

    def create_user(self, username, password=None):
        return self._create_user(username, password, False, True, False)

    def create_superuser(self, username, password):
        user = self._create_user(username, password, True, True, True)

        # gives superusers all the permissions from the get go!
        for x in Permission.objects.all():
            user.permissions.add(x)

        return user

class MyUser(AbstractBaseUser):
    username = models.CharField(max_length=30, unique=True)

    # personal info
    first_name = models.CharField(max_length=30, blank=False)  # blank=False makes the field required
    last_name = models.CharField(max_length=30, blank=False)
    email = models.CharField(max_length=30, blank=False)

    # permissions
    is_staff = models.BooleanField(
        default=False,
        verbose_name='Staff Status',
        help_text='Designates whether the user will have access to the admin interface.'
    )
    is_active = models.BooleanField(
        default=False,
        verbose_name='Active',
        help_text='Recommended to unselect this instead of deleting accounts.'
    )
    is_superuser = models.BooleanField(
        default=False,
        verbose_name='Superuser Status',
        help_text='Designates that this user has all the permissions without explicitly assigning them.'
    )
    groups = models.ManyToManyField(
        Group,
        help_text='Highlighted groups are the ones this user is a member of.',
        blank=True
    )
    permissions = models.ManyToManyField(
        Permission,
        help_text='Highlighted permissions are the ones this user is a member of.',
        blank=True
    )

    # important dates
    date_joined = models.DateTimeField(
        auto_now=False,
        auto_now_add=False,
        default=datetime.datetime.now()
    )

    # other info
    a= models.TextField(max_length=100, blank=False)
    b= models.TextField(max_length=100, blank=False)
    c= models.TextField(max_length=200, blank=False)
    d= models.TextField(max_length=200, blank=False)
    e= models.IntegerField(default=0)
    f= models.IntegerField(default=0)
    g= models.IntegerField(default=0)
    h= models.IntegerField(default=0)

    USERNAME_FIELD = 'username'

    objects = MyUserManager()

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

admin.py

from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group, Permission
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from main.models import MyUser
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.http import HttpResponse
from django.core.mail import send_mail, BadHeaderError, EmailMultiAlternatives
from django.shortcuts import redirect
import csv
import x.settings

# check to see if you are on the production or development branch
# if so then you can import mysql bc the local machine doesn't need mysql
if x.settings.DB_VERSION == 'production' or x.settings.DB_VERSION == 'development':
    import MySQLdb



class UserCreationForm(forms.ModelForm):
    #A form for creating new users

    class Meta:
        model = MyUser
        fields = ('username',
            'password',
            'first_name',
            'last_name',
            'email',
            'is_active',
            'is_superuser',
            'is_staff',
            'groups',
            'permissions',
            'date_joined',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'g',
            'h',
        )

    #def clean_password2(self):
    #    # Check that the two password entries match
    #    password1 = self.cleaned_data.get("password1")
    #    password2 = self.cleaned_data.get("password2")
    #    if password1 and password2 and password1 != password2:
    #        raise forms.ValidationError("Passwords don't match")
    #    return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password("password")
        #user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    #A form for updating users
    class Meta:
        model = MyUser

    def __init__(self, *args, **kargs):
        super(UserChangeForm, self).__init__(*args, **kargs)

        #del self.fields['username']


class MyUserAdmin(UserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = (
        'username',
        'email',
        'first_name',
        'last_name',
        'a',
        'b',
        'is_active'
    )

    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    fieldsets = (
        ('Username and Password', {'fields': ('username', 'password')}),
        ('Personal Info', {'fields': ('first_name', 'last_name', 'email')}),
        ('Permissions', {'fields': ('is_active', 'is_superuser', 'is_staff', 'groups', 'permissions')}),
        ('Important Dates', {'fields': ('last_login', 'date_joined')}),
        ('Other Information', {'fields': ('a', 'b', 'c', 'd', 'e',
            'f', 'g', 'h')})
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username',
            'password',
            'first_name',
            'last_name',
            'email',
            'is_active',
            'is_superuser',
            'is_staff',
            'groups',
            'permissions',
            'date_joined',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'g',
            'h',
            )}
        ),
    )
    search_fields = ('username',)
    ordering = ('username',)
    filter_horizontal = ()


# Now we register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)

最佳答案

如果没有更多上下文,很难说,但我建议您使用 PermissionMixin,除非它提供了您不需要的特定内容。您还需要删除自定义用户模型中与 PermissionMixin 中重复的任何方法或成员。

你可以在这里浏览一下它的方法和成员,https://github.com/django/django/blob/1.5.5/django/contrib/auth/models.py#L293 - 除了更充实的 Perms 方法之外,与自定义模型的唯一重大区别是它包括组支持(这是您需要决定是否想要的。)

关于Django自定义用户模型无法登录管理页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598756/

相关文章:

Django 模型实用程序 : Use InheritanceManager with custom querysets

python-3.x - 如何告诉 Django 模型只有一个或其他字段必须不为空?

django:manytomanyfield with through 如何出现在管理员中?

django - 使用来自另一个 QuerySet : Possible? 的查询过滤 django QuerySet

python - 'str' 对象不支持项目分配 - django 错误

django - Django 内联管理中的模型 "help"文本

python - 在 Django-admin 中,如何显示多对多关系的详细信息

java - 如何从 Django 模板加载 Java 小程序

python - Django:无法运行自定义命令

python - 如何在本地 Django 环境中提供媒体文件?