How can I get the reverse url for a Django Flatpages template

Travis picture Travis · Jul 17, 2009 · Viewed 13.5k times · Source

How can I get the reverse url for a Django Flatpages template

Answer

bufh picture bufh · Jan 11, 2010

I prefer the following solution (require Django >= 1.0).

settings.py

INSTALLED_APPS+= ('django.contrib.flatpages',)

urls.py

urlpatterns+= patterns('django.contrib.flatpages.views',
    url(r'^about-us/$', 'flatpage', {'url': '/about-us/'}, name='about'),
    url(r'^license/$', 'flatpage', {'url': '/license/'}, name='license'),
)

In your templates

[...]
<a href="{% url about %}"><span>{% trans "About us" %}</span></a>
<a href="{% url license %}"><span>{% trans "Licensing" %}</span></a>
[...]

Or in your code

from django.core.urlresolvers import reverse
[...]
reverse('license')
[...]

That way you don't need to use django.contrib.flatpages.middleware.FlatpageFallbackMiddleware and the reverse works as usual without writing so much code as in the other solutions.

Cheers.