Hide action in django admin if they don't have permission

Question:

I added an action in my admin pages that allows user to export selected records to an excel sheet. Now I need to be able to only allow some users to be able to export data. I have a UserProfile model that has a can_export boolean field.

How can I only show the "Export To Excel" action in django admin only if they have the can_export field set as True?

I have tried to find a way in admin.py to get the request object and do a IF statement before setting actions but have had no luck. I get a name’request’ is not defined error of course.

if request.user.get_profile().can_export:
    actions = [export_data()]
Asked By: Austin

||

Answers:

From the FineManual (https://docs.djangoproject.com/en/1.5/ref/contrib/admin/actions/):

    class MyModelAdmin(admin.ModelAdmin):
        ...

        def get_actions(self, request):
            actions = super(MyModelAdmin, self).get_actions(request)
            if request.user.username[0].upper() != 'J':
                if 'delete_selected' in actions:
                    del actions['delete_selected']
            return actions
Answered By: bruno desthuilliers

Only for some users whose can_export is True, you can display export_data admin action by overriding get_actions() as shown below:

# "admin.py"

from django.contrib import admin, messages
from .models import UserProfile

@admin.register(UserProfile)
class UserProfileAdmin(ImportExportModelAdmin):
    actions = ["export_data"]

    def get_actions(self, request):
        actions = super().get_actions(request)
        if not request.user.get_profile().can_export:
            del actions["export_data"]
        return actions

    def export_data(self, request, queryset):

        # Export data

        messages.success(request, "Successfully data is exported!")
Answered By: Kai – Kazuya Ito