About HtttpRequest in Admin Display Functions

Django admin display methods, by default, have no access to the current request, which is necessary to access its properties, context processors, or objects created by middlewares. However, you can set access to the request using this trick:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# posts/admin.py
from django.contrib import admin
from .models import Post

@admin.register(Post):
class PostAdmin(admin.ModelAdmin):
    list_display = ["title", "get_content_html"]

    def get_queryset(self, request):
        self.request = request
        return super().get_queryset(request)

    @admin.display(description="Content")
    def get_content_html(self, obj):
        from django.template.loader import render_to_string

        return render_to_string(
            "admin/posts/post/includes/content_html.html",
            context={"post": obj},
            request=self.request,
        )

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2