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

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


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.


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 reversereverse('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>


I agree with Anentropic that there is no point in using Django Flatpages if you need to write urlconfs to employ them. It's much more straightforward to use generic views such as TemplateView directly:

from django.conf.urls import patterns, urlfrom django.views.generic import TemplateViewurlpatterns = patterns('',    url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"),)

Flatpages take advantage of FlatpageFallbackMiddleware, which catches 404 errors and tries to find content for requested url in your database. The major advantage is that you don't have to touch your templates directly each time you have to change something in them, the downside is the need to use a database :)

If you still choose to use Flatpages app, you'd better use get_flatpages template tag:

{% load flatpages %}<ul>    {% for page in get_flatpages %}        <li><a href="{{ page.url }}">{{ page.title }}</a></li>    {% endfor %}</ul>

Personally, I rarely reference flatpages outside of website's main menu, which is included via {% include 'includes/nav.html' %} and looks like this:

<ul>    <li><a href="/about/">About</a></li>    <li><a href="/credits/">Credits</a></li>    ...</ul>

I don't feel I violate any DRY KISS or something:)