Django管理站点的“身份验证”部分中没有“用户”链接 [英] No “Users” link in “Auth” section of Django admin site

查看:65
本文介绍了Django管理站点的“身份验证”部分中没有“用户”链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在Django应用中创建了一个自定义用户对象,但无法控制用户权限。我相信这是因为用户链接没有出现在Django管理网站的身份验证部分中,该位置通常是对权限进行控制的。

I’ve created a custom user object in my Django app, but don’t have control over user permissions. I believe this is because the Users link isn’t appearing in the Auth section of the Django admin site, where permissions are usually controlled.

为什么不显示?

这是来自我的models.py文件:

This is from my models.py file:

    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

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

In other apps I extend the user model further as needed:

    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)

这是来自我的settings.py文件:

This is from my settings.py file:

    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’

这来自我的urls.py文件:

This is from my urls.py file:

    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)),
    )

这是来自我的admin.py文件:

This is from my admin.py file:

    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的字段集以显示权限

In the end, the solution was rather simple. I had to adjust my CocoUserAdmin’s fieldsets to expose the permissions.

使用这样的自定义类,在Auth部分中将没有用户链接,因为自定义类将接管-包括权限。除非将'groups''user_permissions'添加到<$ c $,否则这些设置将不明显。 c> fieldsets 。

With a custom class like that, there will be no Users link in the Auth section, because the custom class takes over -- including permissions. These settings won’t be evident though, unless 'groups' and 'user_permissions' are added to fieldsets.

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

That CocoUserAdmin fieldsets fix is the key. Along the way, I converted FooUser to be a subclass of AbstractUser. This might have been unnecessary; the permissions may well have been there when CocoUser was a subclass of AbstractBaseUser too, but I’m not sure.

来自我的最终models.py文件:

From my final models.py file:

    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)

从我的最终admin.py文件中:

From my final admin.py file:

    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

这篇关于Django管理站点的“身份验证”部分中没有“用户”链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆