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.
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.
Open a browser on the Django admin site http://127.0.0.1:8000/admin/.
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With