Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 644
Travis Avatar asked Jul 17 '09 17:07

Travis


2 Answers

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.

like image 94
bufh Avatar answered Sep 28 '22 03:09

bufh


Include flatpages in your root urlconf:

from django.conf.urls.defaults import *  urlpatterns = patterns('',     ('^pages/', include('django.contrib.flatpages.urls')), ) 

Then, in your view you can call reverse like so:

from django.core.urlresolvers import reverse  reverse('django.contrib.flatpages.views.flatpage', kwargs={'url': '/about-us/'}) # Gives: /pages/about-us/ 

In templates, use the {% url %} tag (which calls reverse internally):

<a href='{% url django.contrib.flatpages.views.flatpage url="/about-us/" %}'>About Us</a> 
like image 40
elo80ka Avatar answered Sep 28 '22 03:09

elo80ka