pythondjangopermissionsdjango-admindjango-admin-actions

Permissions to Django Admin Actions


I have written some custom actions for my django project, however cannot work out how to make them available to only superusers. I have tried putting an if statement round the actions line with Users.is_superuser but it keeps giving me an error saying there is no attribute called is_superuser.

Here is my admin.py file:

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)

Solution

  • You can customize the list of actions by overriding get_actions(). For example:

    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
    

    Check out https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#conditionally-enabling-or-disabling-actions for more info