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

时间:2014-06-25 19:48:57

标签: python django

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

my admin issue

为什么不出现?

这是来自我的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)

这是来自我的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’

这是来自我的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)),
    )

这是来自我的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)

2 个答案:

答案 0 :(得分:7)

最后,解决方案相当简单。我必须调整我的CocoUserAdmin的fieldsets以公开权限

使用这样的自定义类,Auth部分中将没有Users链接,因为自定义类接管 - 包括权限。但是,除非将'groups''user_permissions'添加到fieldsets,否则这些设置不会显而易见。

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

从我最终的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)

从我最后的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

答案 1 :(得分:0)

我从AbstractUser派生而且遇到了同样的问题。在Auth部分中没有用户。 那是因为我忘了注册我的自定义用户管理类。 也许您需要先注册您的FooUser管理员课程。