我在Django中有一个自定义用户模型。当我从命令行创建新的超级用户时,该用户可以登录管理界面。新的超级用户以is_superuser和is_staff为真开始。现在,当我从管理界面创建一个新的自定义用户时,如果将is_staff和is_superuser设置为true,则该新用户无法登录管理界面。
您是否只需将is_staff设置为true即可登录管理界面?如果是这样,为什么这对从admin界面创建的用户不起作用?
我是否可以更改确定用户是否可以登录管理界面的内容?如果是这样,怎么样!
我很困惑,对此问题的一些见解将不胜感激!提前谢谢!
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
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)
答案 0 :(得分:2)
如果没有更多的上下文,很难说,但我建议您使用PermissionMixin,除非它提供了您不需要的具体内容。您还需要删除自定义用户模型中与PermissionMixin中复制的任何方法或成员。
你可以在这里浏览一下它的方法和成员,https://github.com/django/django/blob/1.5.5/django/contrib/auth/models.py#L293 - 除了更加丰富的perms方法之外,与你的自定义模型唯一的区别在于它包括组支持(这是你需要的决定你是否愿意。)