Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

django-filter compose filtered url

I’m using django-filter and I would like to link to the view with a pre-set filter.

At this time, I’m doing like this:

<a href='{{ url "order_list" }}/?year=2023'>

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

urlnext = (
    reverse('order_list') +
    "?year=2023"
)
return HttpResponseRedirect(urlnext)

I would like to know if exists a more elegant approach. Thanks

>Solution :

Using ?year=2023 is not a good idea. For 2023 this is indeed not a problem. But imagine that the value itself contains a question mark or ampersand, then that would generate a query like ?keyword=foo&bar&key=bar, so it would "cut off" the &bar.

You can work with a QueryDict for this, which is basically what request.GET and request.POST are:

from django.http import QueryDict

qd = QueryDict(mutable=True)
qd['year'] = 2023

return HttpResponseRedirect(f'{reverse('order_list')}?{qd.urlencode()}')

If the value (or key) for example contains an ampersand or question mark, it will percent-encode [wiki] these:

>>> qd.urlencode()
'keyword=foo%26bar%3F'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading