pythondjangodjango-adminuseriddjango-request

How to use `request` in custom `list_display` fields to get the logged-in user's `id` in Django Admin?


I want to create a hyperlink (custom field in display_list) and I have to use logged-in user's id as a part of query parameters in the link.

Is there any solution for this?


Solution

  • You can extend the model admin's get_list_display method to access the request object and you can add your custom method inside that method where it can access the request object.

    from django.utils.html import format_html
    
    Class FooAdmin(admin.ModelAdmin):
       def get_list_display(self, request):
            def custom_url_method(obj):
                user = request.user
                return format_html("<a href='http://url.com/{0}'>link</a>", user.pk)
    
            return ['model_field_1', 'model_field_2', custom_url_method]