[Django]-How to create an article list view in django-cms

4đź‘Ť

âś…

As others have pointed out, the way to do this is by hooking your CMS page to another set of views. Django-CMS provides application hooks:

#cms_app.py
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool

class YourModuleApp(CMSApp):
    name = 'My App MOdule'
    urls = ['my_app.urls']

apphook_pool.register(YourModuleApp)

So, if you had a module called “my_app” with a urls.py in it, Django-CMS will add those patterns to the page. Look in the “Advanced Settings” section of the page in admin for the application drop-down menu.

Once the app is hooked to the page, Django-CMS will pull any content and the layout template from the information it holds, then hand off processing to the additional URL patterns that are hooked to it. That’s how you can pull in another model, add a form, handle a POST, etc.

2đź‘Ť

You could just do it the normal Django way. Create a normal Django app, with a URL pointing to a view that renders a template. The view could look like this:

from django.shortcuts import render
from cms.models import Page

def articles(request):
   pages = Page.objects.public()
   render(request, 'example.html', {'pages': pages})

And the template could look like this:

{% load cms_tags %}
{% for page in pages %}
  <p><a href="{{ page.get_absolute_url }}">{% page_attribute "page_title" page %}</a></p>
{% endfor %}

You could stop here. Or you could have…

Additional Django CMS integration with AppHooks

Do you want your non-developer content managers to be able to put a list of articles wherever they want? This is where AppHooks come in.

Create a CMSApp class in the file appname/cms_app.py like this:

from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _

class ArticleListApp(CMSApp):
    app_name = 'articlelist'
    name = _('Article List')

    def get_urls(self, page=None, language=None, **kwargs):
        return ['articlelist.urls']

apphook_pool.register(YourModuleApp)

Delete the URL entry in your project-wide urls.py as you no longer need it. Your app’s urls.py needs to include a view for the regex ^$.

Now you or any content manager user with necessary permissions can create a page in the admin interface, and modify the advanced settings to select the “Article List” application:

Application and Application instance name page settings

One gotcha is that this will have no effect until the page is published (as well as all of its ancestor pages).

👤Flimm

Leave a comment