Search code examples
djangourldjango-filter

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

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'