Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Django's `urlencode` not encode slash?

I see that Django's urlencode filter doesn't encode slash by default:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#urlencode

I know I can make it encode the slash, but why doesn't it do it by default? Isn't it accepted behavior to encode the slash, given that it's a reserved character in URLs?

like image 948
Ram Rachum Avatar asked Feb 06 '13 00:02

Ram Rachum


People also ask

What does Urllib parse Urlencode do?

parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.

What is the point of Urlencode?

The UrlEncode method converts each space character to a plus character (+). The UrlPathEncode method converts each space character into the string "%20", which represents a space in hexadecimal notation.

Is Urlencode necessary?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.


2 Answers

To get urlencode to also escape / in a Django template, use {{ variable|urlencode:'' }}.

Explanation: The extra optional parameter tells urlencode the set of characters that are "safe", where the default is '/', so passing an empty string is telling urlencode that / is not safe and should be encoded.

like image 158
Rok Strniša Avatar answered Oct 25 '22 13:10

Rok Strniša


From the Django source, urlencode is basically a wrapper around Django's urlquote utility method. From the comments in the source, urlquote is a UTF-8-safe version of urllib.quote.

So urlencode is using the same defaults as python's urllib.quote, and the reason that urllib.quote does not escape slashes can be found in the documentation:

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL. The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'.

So, the reason is that it's escaping the path, and '/' is a perfectly expected and valid character within a path.

like image 31
hrunting Avatar answered Oct 25 '22 12:10

hrunting