What is the correct way to link Django Flatpages?

1.2k Views Asked by At

I have Django 1.8.2 installed in a subdirectory on my server. It is configured with mod_wsgi.py and an Apache2 and is running properly.

The Django application is accessible under https://example.com/django and everything is configured and running fine.

Now I want to use Flatpages and link them in my templates. I do it like this:

<a href="/my-flatpage/">Awesome!</a>

This works on the dev server on my local machine. But when I deploy it on my server, clicking on the link results in this url: https://example.com/my-flatpage/ which is natural, because this is how I referenced it in the a tag.

But how can I do it properly, no matter if django is stored in a subdirectory or not? I do not want to hardcode the subdirectory /django/, because this is just a testing server. There must be a better solution than this. Can you explain me please, how I should link my flatpages in my templates? I think there must be a way to include the correct path to the flatpage, no matter if Django is stored in a subdirectory or in root.

I tried to give them names in urls.py and hardcoded the links. But the testing server was not able to produce the correct links (the local dev webserver provided by django did!) and I do not think it is a good solution to write the urls twice into my application (first in the definition of the flatpage, second in the urls.py). With the named urls I tried to link to the pages with

<a href="{% url 'my-flatpage' %}">Awesome!</a>

Worked locally, but not on the testing server.

I have Middleware enabled for Flatpages:

MIDDLEWARE_CLASSES = (
    ...
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    ...
)

I know that a link starting with / refers to the root. Therefore it skips the subdirectory, where it is actually stored in. I just don't know how to make proper links even if Django is installed in a subdirectory.

Thanks for your help!

1

There are 1 best solutions below

1
On BEST ANSWER

When using the middleware, there's no good solution. When using the urls.py, it's easy: https://docs.djangoproject.com/en/dev/ref/contrib/flatpages/#using-the-urlconf

You can make them explicit:

from django.contrib.flatpages import views

urlpatterns += [
    url(r'^about-us/$', views.flatpage, {'url': '/about-us/'}, name='about'),
    url(r'^license/$', views.flatpage, {'url': '/license/'}, name='license'),
]

Or just the view:

from django.contrib.flatpages import views

# Your other patterns here
urlpatterns += [
    url(r'^(?P<url>.*/)$', views.flatpage, name='flatpage'),
]

Combined with urls like these:

<a href="{% url 'about' %}">About</a>
<a href="{% url 'about' %}">License</a>
<a href="{% url 'flatpage' url='/some_other_page/' %}">Some other page</a>