Search code examples
djangodjango-adminrequest

Django Admin: How to access the request object in admin.py, for list_display methods?


I've added a method highlight_link to my model's admin.py class:

class RadioGridAdmin(admin.ModelAdmin):
    
    list_display = ('start_time', highlight_link)
    
    def highlight_link(self):
        return ('some custom link')
    
    
admin.site.register(RadioGrid, RadioGridAdmin)

It returns a custom link for (I've left out highlight_link.short_description for brevity) each record returned in the change list. Which is great. But I'd like to inspect the current query string and change the custom link based on that. Is there a way to access the request object within highlight_link?


Solution

  • I tried the other answers left here and ran into issues that for me, were getting complex. I played around with def __call__() and came up with the following. This probably isn't the correct way to do this, but it works...

    grab the GET variable here (all within class RadioGridAdmin as described above in my initial post):

    def __call__(self, request, url):
         global start_date
         start_date = request.GET['param']
    
         return super(RadioGridAdmin, self).__call__(request, url)
    

    and since it's global, you can now access it here:

    def highlight_link(self):
        # access start_date here