Using Django flatpages content in other (class-based) views

The flatpages application that ships with Django is both (intentionally) simple and useful. In previous projects I’ve found myself both extending the models (to add data like meta tags) and duplicating the whole application (when I wanted to add a whole bunch of extra details, multiple content sections, or a WYSIWYG editor).

In a recent project I had the need to editable (by administrators) content in other views, and I turned to flatpages again for my solution.

What I did was to create a class-based view mixin to find the flatpage for a given URL (defaulting to the one defined in request.path), and include the resulting object in the context (once the title and content had been marked safe of course):

from django.contrib.flatpages.models import FlatPage


class FlatPageMixin(object):
    """
    Retrieves the FlatPage object for the specified url, and includes it in the
    context.

    If no url is specified, request.path is used.
    """
    url = None

    def get_context_data(self, **kwargs):
        if not self.url:
            self.url = self.request.path

        context = super(FlatPageMixin, self).get_context_data(**kwargsG)
        try:
            flatpage = FlatPage.objects.get(url=self.url)
            flatpage.title = mark_safe(flatpage.title)
            flatpage.content = mark_safe(flatpage.content)
            context["flatpage"] = flatpage
        except FlatPage.DoesNotExist:
            context["flatpage"] = None

        return context

Then you just need to ensure a flatpage exists for the expected (or specified) URL, add the mixin to your class-based view(s) and use {{ flatpage.title }} and {{ flatpage.content }} in the template(s).