gpt4 book ai didi

python - Django 管理站点的 “Users” 部分中没有 “Auth” 链接

转载 作者:太空狗 更新时间:2023-10-30 02:20:15 26 4
gpt4 key购买 nike

我在我的 Django 应用程序中创建了一个自定义用户对象,但无法控制用户权限。我相信这是因为用户链接没有出现在 Django 管理站点的 Auth 部分中,该部分通常控制权限。

my admin issue

为什么不显示?

这是来 self 的 models.py 文件:

    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models


class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a user with the given username.
"""
user = self.model()
user.username = username
user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username.
"""
user = self.create_user(username, password=password)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user


class FooUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=40, unique=True, db_index=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
my_time_field = models.DateTimeField(null=True, blank=True)

USERNAME_FIELD = 'username'

objects = UserManager()

class Meta:
app_label = 'foo'

def get_full_name(self):
return self.username

def get_short_name(self):
return self.username

def has_perm(self, perm, obj=None):
return self.is_admin

def has_module_perms(self, app_label):
return self.is_admin

在其他应用中,我根据需要进一步扩展用户模型:

    class CocoUser(FooUser):
mobile_number = models.CharField(max_length=64, blank=True, null=True)
first_name = models.CharField(max_length=128, blank=True, null=True)
last_name = models.CharField(max_length=128, blank=True, null=True)
email = models.CharField(max_length=128, blank=True, null=True)

这是来 self 的 settings.py 文件:

    MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'kohlab.force_logout.ForceLogoutMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.humanize',
'django.contrib.messages',
'django_cleanup',
'south',
'myapp',
)

TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.static",
"kohlab.context_processors.site",
)

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)

AUTH_USER_MODEL = ‘myapp.FooUser’

这是来 self 的 urls.py 文件:

    from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)

这是来 self 的 admin.py 文件:

    from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from coco.models import CocoUser


class CocoUserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required fields, plus a repeated password."""

class Meta:
model = CocoUser
fields = ('mobile_number', 'email', 'first_name', 'last_name',)


class CocoUserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on the user, but replaces the password field with the initial one.
"""
class Meta:
model = CocoUser
fields = ['is_admin', 'is_staff', 'mobile_number', 'first_name', 'last_name', 'email']

def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the field does not have access to the initial value
return self.initial["password"]


class CocoUserAdmin(UserAdmin):
# The forms to add and change user instances
form = CocoUserChangeForm
add_form = CocoUserCreationForm

# The fields to be used in displaying the CocoUser model.
# These override the definitions on the base UserAdmin that reference specific fields on auth.User.
list_display = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'is_admin', 'is_staff',)
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('is_admin', 'is_staff', 'mobile_number', 'first_name', 'last_name', 'email',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('mobile_number', 'email', 'first_name', 'last_name',)}
),
)
search_fields = ('id', 'mobile_number', 'email', 'first_name', 'last_name',)
ordering = ('last_name', 'first_name',)
filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(CocoUser, CocoUserAdmin)

最佳答案

最终,解决方案相当简单。我不得不调整我的 CocoUserAdmin 的fieldsets 以公开权限

使用这样的自定义类,Auth 部分将没有用户链接,因为自定义类接管了——包括权限。这些设置不会很明显,除非 'groups''user_permissions' 被添加到 fieldsets

CocoUserAdmin fieldsets 修复是关键。在此过程中,我将 FooUser 转换为 AbstractUser 的子类。这可能是不必要的;当 CocoUser 也是 AbstractBaseUser 的子类时,权限可能已经存在,但我不确定。

来 self 最终的 models.py 文件:

    from django.contrib.auth.models import AbstractUser
from django.db import models


class FooUser(AbstractUser):
my_time_field = models.DateTimeField(null=True, blank=True)

class CocoUser(FooUser):
mobile_number = models.CharField(max_length=64, blank=True, null=True)

来 self 最终的 admin.py 文件:

    from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from coco.models import CocoUser


class CocoUserCreationForm(forms.ModelForm):
"""A form for creating new users."""

class Meta:
model = CocoUser
fields = ('username', 'mobile_number', 'email', 'first_name', 'last_name',)


class CocoUserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on the user.
"""
class Meta:
model = CocoUser
fields = ['username', 'password', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', 'last_login', 'date_joined',
'my_time_field', 'mobile_number',]


class CocoUserAdmin(UserAdmin):
# The forms to add and change user instances
form = CocoUserChangeForm
add_form = CocoUserCreationForm

# The fields to be used in displaying the CocoUser model.
# These override the definitions on the base UserAdmin that reference specific fields on auth.User.
list_display = ('id', 'first_name', 'last_name', 'email', 'mobile_number',)
fieldsets = (
(None, {'fields': ('username', 'password',)}),
('Personal info', {'fields': ('first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_online',)}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions',)}),
('Coco', {'fields': ('my_time_field', 'mobile_number',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'mobile_number', 'email', 'first_name', 'last_name',)}
),
)
search_fields = ('id', 'mobile_number', 'email', 'first_name', 'last_name',)
ordering = ('last_name', 'first_name',)

class Meta:
model = CocoUser

关于python - Django 管理站点的 “Users” 部分中没有 “Auth” 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24417303/

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