Django Admin: How to access the request object in admin.py, for list_display methods?
I solve my issue this way.
class MyClassAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(MyClassAdmin, self).queryset(request)
self.request = request
return qs
Now i can use self.request
in any place
UPDATE
Changed in Django 1.6: The get_queryset method was previously named queryset.
class MyClassAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyClassAdmin, self).get_queryset(request)
self.request = request
return qs
class RadioGridAdmin(admin.ModelAdmin):
def highlight_link(self, obj):
return (self.param)
def changelist_view(self, request, extra_context=None):
self.param = request.GET['param']
return super(RadioGridAdmin,self).changelist_view(request, extra_context=extra_context)
Described how to refactor this into a mixin, with addition of the thread-safety bit based on @taha-jahangir's answer. Here's the mixin:
import threading
class ModelAdminRequestMixin(object):
def __init__(self, *args, **kwargs):
# let's define this so there's no chance of AttributeErrors
self._request_local = threading.local()
self._request_local.request = None
super(ModelAdminRequestMixin, self).__init__(*args, **kwargs)
def get_request(self):
return self._request_local.request
def set_request(self, request):
self._request_local.request = request
def changeform_view(self, request, *args, **kwargs):
# stash the request
self.set_request(request)
# call the parent view method with all the original args
return super(ModelAdminRequestMixin, self).changeform_view(request, *args, **kwargs)
def add_view(self, request, *args, **kwargs):
self.set_request(request)
return super(ModelAdminRequestMixin, self).add_view(request, *args, **kwargs)
def change_view(self, request, *args, **kwargs):
self.set_request(request)
return super(ModelAdminRequestMixin, self).change_view(request, *args, **kwargs)
def changelist_view(self, request, *args, **kwargs):
self.set_request(request)
return super(ModelAdminRequestMixin, self).changelist_view(request, *args, **kwargs)
def delete_view(self, request, *args, **kwargs):
self.set_request(request)
return super(ModelAdminRequestMixin, self).delete_view(request, *args, **kwargs)
def history_view(self, request, *args, **kwargs):
self.set_request(request)
return super(ModelAdminRequestMixin, self).history_view(request, *args, **kwargs)
Subclass ModelAdmin with the mixin:
class PollAdmin(ModelAdminRequestMixin, admin.ModelAdmin):
pass
... and you can just call self.get_request()
from any method.