react
react

Reputation: 179

How to get current user in custom methods in Django Admin?

So, I have this code

class PostAdmin(models.ModelAdmin):
    # ...
    def display_confirm_button(self, obj):
        # some code
    # ...

How to get current user in display_confirm_button method?

Upvotes: 2

Views: 2907

Answers (2)

Benedetto Campanale
Benedetto Campanale

Reputation: 31

The best solution IMHO is to store the current user in changelist_view to have it accessible in your method.

class PostAdmin(models.ModelAdmin):
    def changelist_view(self, request, extra_context=None):
        setattr(self, 'user', request.user)
        return super().changelist_view(request, extra_context)

    def display_confirm_button(self, obj):
        # you can use self.user here

You can keep this DRY by creating a mixin like this:

class CurrentUserMixin(object):
    def changelist_view(self, request, extra_context=None):
        setattr(self, 'user', request.user)
        return super().changelist_view(request, extra_context)


class PostAdmin(CurrentUserMixin, models.ModelAdmin):
    def display_confirm_button(self, obj):
        # you have self.user here

Upvotes: 3

Alasdair
Alasdair

Reputation: 308779

class PostAdmin(models.ModelAdmin):
    # ...
    def display_confirm_button(self, obj):
        # some code
    # ...

To access the logged in user, you need access to the request object. It isn't possible to access the request in your display_confirm_button method, since you only have access to obj, the object that is being edited.

The solution is to override get_list_display, which has access to the request object. You can then define your display_confirm_button inside get_list_display where it has access to the request, and include the display_confirm_button callable in the list that you return.

class MyModelAdmin(admin.ModelAdmin):
    def get_list_display(self, request):

        def display_confirm_button(obj):
            out = logic_that_requires_user(request.user)
            return out

        return ['field1', 'field2', display_confirm_button, ...]

Upvotes: 7

Related Questions