Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URLs - can't reverse url in a template

Tags:

I think I need a second pair of eyes.

The below example should be self explanatory.

All I need is to be able to reverse my url in the template.

/urls.py

urlpatterns = patterns('',     (r'^products/', include('products.urls')), ) 

/products/urls.py

from django.conf.urls.defaults import patterns, url  urlpatterns = patterns('products.views',     url(r'^$', view="index", name="index"), ) 

/templates/products/index.html

<a href="{% url products:index %}"> Products </a> 

UPDATE

Full stacktrace - http://pastebin.com/9nLp4uP5

like image 527
howtodothis Avatar asked Nov 23 '11 05:11

howtodothis


People also ask

How do I reverse in Django?

reverse() If you need to use something similar to the url template tag in your code, Django provides the following function: reverse (viewname, urlconf=None, args=None, kwargs=None, current_app=None)

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How do I return a URL in Django?

Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .


2 Answers

The syntax changed after Django 1.5 Instead of doing this:

<a href="{% url products_index %}"> Products </a>

You should now do this(string instead):

<a href="{% url 'products_index' %}"> Products </a>

like image 163
JOSEFtw Avatar answered Oct 27 '22 13:10

JOSEFtw


You might try this instead:

urlpatterns = patterns('products.views',     url(r'^$', view="index", name="products_index"), ) 

/templates/products/index.html

<a href="{% url products_index %}"> Products </a> 

Unless there's a compelling reason you want to namespace your urls, it's way easier just to use a more precise name in urls.py and then use that name in the url template tag.

Update

If the error you're getting is No module named urls then that means one of the urls.py files isn't being read in by the django project. Did you make sure that products has been added to INSTALLED_APPS in the settings.py file? Also, please include a stacktrace in your question so it will be easier to identify where the error is taking place.

like image 30
Jordan Reiter Avatar answered Oct 27 '22 13:10

Jordan Reiter