我注意到Django的urlencode
过滤器默认不对斜杠进行编码:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#urlencode
我知道可以让它对斜杠进行编码,但为什么它不会默认这样做呢?考虑到斜杠在URL中是一个保留字符,对其进行编码不是一种被接受的行为吗?
我注意到Django的urlencode
过滤器默认不对斜杠进行编码:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#urlencode
我知道可以让它对斜杠进行编码,但为什么它不会默认这样做呢?考虑到斜杠在URL中是一个保留字符,对其进行编码不是一种被接受的行为吗?
urlencode
基本上是Django的urlquote
实用程序方法的包装器。从源代码中的注释可以看出,urlquote
是urllib.quote
的UTF-8安全版本。urlencode
使用与Python的urllib.quote
相同的默认值,urllib.quote
不转义斜杠的原因可以在documentation中找到:'/'
是路径中完全预期和有效的字符。要在Django模板中使urlencode
转义/
,请使用{{ variable|urlencode:'' }}
。
解释:额外的可选参数告诉urlencode
哪些字符是“安全”的,其中默认值为'/'
,因此传递空字符串告诉urlencode
不安全并应该编码/
。