如何在 django 管理员上按用户组隐藏特定字段

How to hide specific field by User Group on a django admin

我想通过权限或组隐藏我的 Django 管理模型的特定行

我的models.py

class Post(models.Model):
    title = models.CharField(max_length=128)
    slug = AutoSlugField(populate_from='title')
    category = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='actus')
    is_verified = models.BooleanField(default=False)
    content = RichTextField(blank=True, null=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    thumbnail = models.ImageField(upload_to='media/thumbs', blank=True, null=True, default="media/thumbs/default.jpg")
    date = models.DateTimeField(auto_now_add=True, blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("post", kwargs={"slug": self.slug, "category": self.category})

我的模型管理员

from django.contrib import admin
from django.db import models
from django.db.migrations.graph import Node
from django.utils.regex_helper import Group

from .....models import Post


class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'date', 'is_verified')
    list_filter = ('date', 'author', 'is_verified')


admin.site.site_header = 'Staff Dashboard'
admin.site.register(Post, PostAdmin)

我的 django 管理页面 Django admin page

如果有人有想法

您可以定义两个 ModelForm:一个有 is_verified 选项,一个没有,所以:

# app_name/forms.py

from django import forms
from app_name.models import Post

class NormalUserPostForm(forms.ModelForm):
    class Meta:
        model = Post
        <strong>exclude = ['is_verified']</strong>

class AdminUserPostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'

然后我们可以覆盖ModelAdminget_form方法:

# app_name/admin.py

from app_name.forms import <strong>NormalUserPostForm, AdminUserPostForm</strong>

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'date', 'is_verified')
    list_filter = ('date', 'author', 'is_verified')
    <strong>form = NormalUserPostForm</strong>

    def get_form(self, request, obj=None, **kwargs):
        if request.user.is_superuser:
            <strong>kwargs['form'] = AdminUserPostForm</strong>
        return super().get_form(request, obj, **kwargs)


admin.site.site_header = 'Staff Dashboard'
admin.site.register(Post, PostAdmin)

你可以把条件改成request.user.has_perm('<em>some_permission</em>')来检查某个权限。