Skip to content
Advertisement

How to get request params in Django admin custom column?

I need to keep information about filtering and searching in Django admin change page.

So when user filters by "?away_team__id__exact=267821", I need to append this query to change page url.

Let’s say we filtered objects by query above. This is the url of change list:

http://127.0.0.1:8000/matches/match/?away_team__id__exact=267821

I want to make change column which redirects user to change page of the current object and appends query to the url so instead:

http://127.0.0.1:8000/matches/match/2009/change/

The url will be:

http://127.0.0.1:8000/matches/match/2009/change/?away_team__id__exact=267821

The problem is that I couldn’t access request in the custom column method. I tried to do it using template language but without success, I get:

http://127.0.0.1:8000/matches/match/1996/change/?{{%20request.GET.urlencode%20}}

This is the method:

def change(self,obj):
    return mark_safe(f"""<a class="changelink" href="{reverse("admin:matches_match_change",args=(obj.pk,))}"""+"?{{ request.GET.urlencode }}""+"><span class='icon'>ZmeniƄ</span></a>")

Do you know how to do that?

EDIT

This is because I need to create a NEXT and PREVIOUS buttons in change object page so user can step directly to the next object.

Advertisement

Answer

You can just store the current request on the admin instance in the change list view to make it available to subsequent methods:

class YourAdmin(ModelAdmin):
    def changelist_view(self, request, *args, **kwargs):
        self.request = request
        return super().changelist_view(request, *args, **kwargs)

    def change(self, obj):
        request = getattr(self, 'request', None)
        if request:
           # use request.GET to construct the link
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement