Django自定义用户模型不能登录到Admin页面

时间:2022-11-19 19:21:18

I have a custom user model in Django. When I create a new superuser from the command line, that user can log into the admin interface. That new superuser starts off with is_superuser and is_staff as true. Now, when I create a new custom user from the admin interface, with is_staff and is_superuser set to true, that new user cannot log into the admin interface.

我在Django中有一个自定义用户模型。当我从命令行创建一个新的超级用户时,该用户可以登录到管理界面。新的超级用户以is_superuser和is_staff作为开始。现在,当我从admin界面创建一个新的自定义用户时,is_staff和is_superuser设置为true,新用户不能登录到管理界面。

Don't you just need to have is_staff set to true to log into the admin interface? If so, why is this not working for users created from admin interface?

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

Could I potentially change what determines if users can log into the admin interface? If so, how!

我是否可以修改什么决定用户是否可以登录到管理界面?如果是这样,如何!

I am thoroughly confused, and some insight into this problem would be much appreciated! Thanks in advance!

我完全搞不懂,对这个问题的一些见解将非常感谢!提前谢谢!

models.py

models.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

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)

1 个解决方案

#1


2  

It's hard to say without more context, but I'd suggest that you use the PermissionMixin unless there are specific things it provides that you don't need. You'll also want to remove any methods or members of your custom user model which duplicate those in the PermissionMixin.

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

You can glance over its methods and members here, https://github.com/django/django/blob/1.5.5/django/contrib/auth/models.py#L293 - other than more fleshed out perms methods, the only big difference from your custom model is that it includes group support (which is what you'll need to decide if you want or not.)

您可以浏览它的方法和成员,https://github.com/django/django/blob/1.5.5/django/auth/models.py #L293——除了更丰富的perms方法之外,与您的自定义模型的唯一大区别在于它包含了组支持(这是您需要决定是否需要的内容)。

#1


2  

It's hard to say without more context, but I'd suggest that you use the PermissionMixin unless there are specific things it provides that you don't need. You'll also want to remove any methods or members of your custom user model which duplicate those in the PermissionMixin.

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

You can glance over its methods and members here, https://github.com/django/django/blob/1.5.5/django/contrib/auth/models.py#L293 - other than more fleshed out perms methods, the only big difference from your custom model is that it includes group support (which is what you'll need to decide if you want or not.)

您可以浏览它的方法和成员,https://github.com/django/django/blob/1.5.5/django/auth/models.py #L293——除了更丰富的perms方法之外,与您的自定义模型的唯一大区别在于它包含了组支持(这是您需要决定是否需要的内容)。