Flatpages is an application that allows Django to create dynamic pages that come with itself. In this article we will talk about how to use it. To do this, we need to include the application in our project first.
How to Install Django Flatpages
1 2 3 4 5 | INSTALLED_APPS = ( .... 'django.contrib.sites', 'django.contrib.flatpages', ) |
The flatpages application, which you should pay attention to here, uses the sites application, and the sites application must also be included in the project. Another point to consider is the following line for the sites application: settings.py we need to add the file.
1 | SITE_ID = 1 |
After this we add the following line to the MIDDLEWARE_CLASSES:
1 2 3 4 | MIDDLEWARE_CLASSES = ( .... 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ) |
Let’s configure the URL.
1 2 3 4 | urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^pages/', include('django.contrib.flatpages.urls')), ) |
We have imported the URL file of the flatpages application. After that, we create a page from the admin panel by creating the database.
1 | python manage.py syncdb |
We are now ready to create a dynamic page. When you open the admin panel, you will see the flat pages field. Create a new one by clicking on it.
How to Build Dynamic Page with Flatpage Django
If we try to go to the URL we created in /pages/Lorem-ipsum/ flatpages/default.we get an error like HTML was not found. To do this, under the templates directory, flatpages/default.html Create HTML. And here’s what we’re writing.
1 2 3 4 5 6 7 8 9 | <html> <head lang="en"> <meta charset="UTF-8"> <title>{{ flatpage.title }}</title> </head> <body> {{ flatpage.content }} </body> </html> |
Now again http://localhost:8000/pages/lorem-ipsum/ if you try to go to the address you will see the page opens. Flatpages/default.html, where we leave the Template Name field blank when creating the page.searching for the HTML template.
Another method of use is as follows. We can define the URL as follows.
1 2 3 4 | urlpatterns = patterns('', ... url(r'/lorem-ipsum/$', 'django.contrib.flatpages.views.flatpage', kwargs={'url': '/lorem-ipsum/'}, name='lorem_ipsum'), ) |
If you delete the previous URL definition. After defining this URL http://localhost:8000/lorem-ipsum you can access the browser again with the/ address. If you enter any name in the Template Name field in the Advanced Options section when entering flat plate from the admin panel, this page will now be redirected to the template you entered.
We can also make the URL definition as follows.
1 2 3 | urlpatterns += patterns('django.contrib.flatpages.views', (r'^pages/(?P<url>.*/)$', 'flatpage'), ) |
With the following HTML output, you can list flatpages.
1 2 3 4 5 6 7 | {% load flatpages %} {% get_flatpages as flatpages %} <ul> {% for page in flatpages %} <li><a href="{{ page.url }}">{{ page.title }}</a></li> {% endfor %} </ul> |