Use double quotes for {% url %} on Django

Grab the feed

School is a twelve-year jail sentence where bad habits are the only curriculum truly learned.

John Taylor Gatto

Recent comments

I recently commented about using the right quotes with Python and simplejson and today I found a similar issue with Django.

It happens when using the {% url %} tag on the template system in Django 1.0. {% url %} helps you to avoid hardcoding links and relies on naming your url patterns.

Let's suppose we have a url like this in our URLConf:

url(r'^add/chatroom/(?P\w+)$', 'myapp_chatroom_add', name='myapp_chatroom_add'),

Now you could insert {% url %} in your template to get the url for a link:

{% url myapp_chatroom_add chatroom_data="abc" %}

Notice I'm passing the string "abc" using double quotes as the chatroom_data parameter.

And here's the important part, these two won't work:

{% url myapp_chatroom_add chatroom_data=abc %}

which does not use quotes at all, or this one:

{% url myapp_chatroom_add chatroom_data='abc' %}

which uses single quotes.

The errors may vary depending on how your code works but the fact is to remember that when passing string based parameters to {% url %} you need to always use double quotes.

If you're using numbers you could use either no quotes or double quotes. Single quotes will never work.

Join the conversation

Actually it's a common bug:

Actually it's a common bug.

thanks for the article.

thanks for the article. moreover, how can i add jscript variable into url like:

function Reload(){
var param_1 = jQuery("#some_code").val();
var param_url = '{% url view_handler p_1=param_1 %}';
jQuery("#list").jqGrid('setGridParam',{ url: my_url }).trigger("reloadGrid");
}

Keep your comments relevant, written in good English and don't spam. Let's create useful and valuable discussions. Markdown is welcome.

Add your comment