我已经为我的django项目编写了一些自定义操作,但是无法解决如何让它们仅供超级用户使用。我已经尝试在使用Users.is_superuser的操作行周围添加一个if语句,但它一直给我一个错误,说没有名为is_superuser的属性。
这是我的admin.py文件:
from django.contrib import admin
from models import Art, Agent, UserProfile
from django.contrib import admin
from django.contrib.auth.models import Group, User, AbstractUser
from django.contrib.auth import *
from import_export import resources
from import_export.admin import ImportExportModelAdmin
#admin.site.unregister(Group)
def approve_art(modeladmin, request, queryset):
queryset.update(authenticate = "approved")
def reject_art(modeladmin, request, queryset):
queryset.update(authenticate = "rejected")
# Add in this class to customized the Admin Interface
class ArtAdmin(ImportExportModelAdmin):
list_display = ['id', 'identification', 'name', 'artist', 'category', 'type', 'agent', 'authenticate', ]
search_fields = ('name', 'category', 'artist', 'id', 'authenticate', )
actions = [approve_art, reject_art]
list_filter = ["authenticate"]
class AgentAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'phone', 'postcode', ]
search_fields = ('name', 'id', )
class ArtResource(resources.ModelResource):
class Meta:
model = Art
# Update the registeration to include this customised interface
admin.site.register(Art, ArtAdmin)
admin.site.register(Agent, AgentAdmin)
答案 0 :(得分:3)
您可以通过覆盖get_actions()
来自定义操作列表。例如:
class ArtAdmin(ImportExportModelAdmin):
list_display = ['id', 'identification', 'name', 'artist', 'category', 'type', 'agent', 'authenticate', ]
search_fields = ('name', 'category', 'artist', 'id', 'authenticate', )
list_filter = ["authenticate"]
actions = [approve_art, reject_art]
def get_actions(self, request):
actions = super(ArtAdmin, self).get_actions(request)
if not request.user.is_superuser:
del actions[approve_art]
del actions[reject_art]
return actions
答案 1 :(得分:0)
您可以像这样覆盖ModelAdmin的get_actions
方法:
def get_actions(self, request):
actions = super(MyModelAdmin, self).get_actions(request)
if request.user.is_superuser:
actions.update(dict(youraction=youraction))
return actions
您可能需要查看documentation materials。
答案 2 :(得分:0)
考虑到某个操作不依赖于ModelAdmin
,防止它被非授权用户运行的最佳方法仍然是在操作中检查它:
from django.core.exceptions import PermissionDenied
def approve_art(modeladmin, request, queryset):
if not request.user.is_superuser:
raise PermissionDenied
queryset.update(authenticate = "approved")
哪个是how django handles it for the delete_selected
action。
虽然该操作仍会在下拉列表中保持可用,但会返回403 HTTP代码。
答案 3 :(得分:0)
更新Django> = 2.1
https://docs.djangoproject.com/en/2.2/ref/contrib/admin/actions/#setting-permissions-for-actions
简而言之:
no-process-env
或自定义:
def make_published(modeladmin, request, queryset):
queryset.update(status='p')
make_published.allowed_permissions = ('change',)
(示例代码均取自链接文档。)