Django ulr does not accept query string

Viewed 24

I have a view in Django that redirects a user to some url with aditional query string:

return redirect('search/?print_id='+str(pk))

In my urls.py, the url pattern looks like this:

path('search/', views.search, name='search'),

And the problem is when Django tries to redirect, I get the following error:

Reverse for 'search/?print_id=36' not found. 'search/?print_id=36' is not a valid view function or pattern name.

How can I modify the url pattern to accept a query string?

1 Answers

redirect will try to look for a view with that name. You should work with a :

from django.http import HttpResponseRedirect, QueryDict
from django.urls import reverse

# …

qd = QueryDict(mutable=True)
qd['print_id'] = pk
return HttpResponseRedirect(f"{reverse('search')}?{qd.urlencode()}")
Related