AlanTheKnight
AlanTheKnight

Reputation: 96

How can I use .format() with urls in Django?

I'm writing an app in Django and I would like to format my url in this way:

return HttpResponseRedirect("timetable/{0}/{1}/".format(my_grade, my_letter))

But it gives me 404 error because path doesn't match. It's the url I'm redirected to:

http://127.0.0.1:8000/timetable/8/%D0%97/

How can I fix encoding?

Upvotes: 0

Views: 474

Answers (2)

AlanTheKnight
AlanTheKnight

Reputation: 96

Finally I got to the answer. The right way was to use urllib.parse.unquote() function which replaces %xx escapes by their single-character equivalent.

from urllib.parse import unquote

url = str(my_grade) + '/' + my_letter
url = unquote(url)
return HttpResponseRedirect(url)

Upvotes: 0

Gocht
Gocht

Reputation: 10256

From urlparse

from urllib.parse import urlparse

parsed = urlparse("timetable/{0}/{1}/".format(my_grade, my_letter))
url = parsed.path

return HttpRedirect(url)

Upvotes: 1

Related Questions