Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin - how to get the current url parameters in python

Here I made an example of what I have in my admin.py:

@admin.register(Car)
class CarAdmin(CustomAdmin):
    list_display = ('get_color',)
    def get_color(self, obj):
        return mark_safe('<a href="/admin/myapp/car/?color={}">{}</a>'.format(obj.color, obj.color))

I have produced a link that can be used to display cars with a specific color. Let's say the page is currently showing cars that cost less than $20k and I want this link to preserve the current filter. Any ideas how to do that? Maybe there is a way to get the current url from python.

Note that I know I can write a javascript to modify the links after the page is loaded, but that is a terrible solution.

like image 866
max Avatar asked Dec 12 '17 19:12

max


People also ask

How do I get parameter data in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.

How do I find my Django admin URL?

Open a browser on the Django admin site http://127.0.0.1:8000/admin/.

How can I get previous URL in Django?

You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.


1 Answers

You can save the full path or request before the get_color is called, something like:

class CarAdmin(CustomAdmin):
    list_display = ('get_color',)

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

    def get_color(self, obj):
        return mark_safe('<a href="{}&color={}">{}</a>'.format(self.full_path, obj.color, obj.color))  # Need to handle empty query paramrers.. 
like image 107
ahmed Avatar answered Sep 22 '22 19:09

ahmed