[Answered ]-Django-filter compose filtered url

1👍

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'

0👍

You can try alternative ways to achieve the same result using Django’s urlencode function to construct the query parameters.

from django.utils.http import urlencode

filter_values = {'year': '2023'}  

url = f"{reverse('order_list')}?{urlencode(filter_values)}"

return HttpResponseRedirect(url)

Leave a comment