I'm having an issue where the template url reversal is escaping colon and parenthetical characters. I want these characters to remain unescaped in the anchor tag's href attribute. It used to behave this way when I was in django 1.3, but upgrading to 1.6, I notice that this does not behave as I want.
What I have:
surt = 'http://(gov/'
browse_domain = 'gov'
... in template ...
<a href="{% url 'nomination.views.url_surt' project.project_slug surt %}">{{ browse_domain }}</a>
This yields:
<a href="/nomination/eth2008/surt/http%3A//%28gov/">gov</a>
As you can see, the colon :
and left parenthetical (
characters are being escaped in the url href attribute. I don't want that.
What I want:
surt = 'http://(gov/'
browse_domain = 'Gov'
... in template ...
<a href="{% url 'nomination.views.url_surt' project.project_slug surt %}">{{ browse_domain }}</a>
This yields:
<a href="/nomination/eth2008/surt/http://(gov/">gov</a>
Anyone know how to keep these characters from escaping when I'm reversing URLs in my anchor tag?
NOTE: The below answer is wrong. urllib.quote(safe=':()') will indeed keep those safe characters unescaped. Something else is happening in django to cause this problem and I still don't know where it is.
In Django 1.6, any url reversal in the template will first pass through
iri_to_uri()
before it is rendered to HTML. There is no override for this in the template call to url reverse{% url %}
as-is.Notice this bit of italicized text detailing the change.
This is
iri_to_uri()
At first glance, this might look like
:
,(
, and)
are safe from escaped hex-encoding because they are passed as 'safe' tourllib.quote()
:If you step through the actual
urllib.quote()
method as shown above, 'safe' actually means that those characters will be escaped/quoted. Initially, I thought 'safe' meant 'safe-from-quoting'. It caused me a great deal of confusion. I guess they instead mean, 'safe' as 'safe-in-terms-of-sections-2.2-and-2.3-of-RFC-3986'. Perhaps a more elaborately named keyword argument would be prudent, but then again, there's a whole cornucopia of things I find awkward regardingurllib
. ಠ_ಠAfter much research, and due to the fact that we don't want to modify Django core methods, our team decided to do some hacky url-construction in the template (the very kind Django docs strongly eschew). It's not perfect, but it works for our use case.