Simple Flatpage Navigation Items

Flatpages are great for simple html content. However, I wanted some way to associate a navigation menu (just a snippet of HTML) with one or more FlatPage objects. Additionally, I wanted to be able to edit these throught the Admin. This is the best solution I found on django snippets.

# models.py

from django.db import models
from django.contrib.flatpages.models import FlatPage

class FlatpageNav(models.Model):
    '''
    A simple snippet of HTML that can be associated with multiple FlatPages.
    '''
    flatpages = models.ManyToManyField(FlatPage, 
        help_text='Select the Flatpages that should display this menu')
    name = models.CharField(max_length=255, 
# models.py

from django.db import models
from django.contrib.flatpages.models import FlatPage

class FlatpageNav(models.Model):
    '''
    A simple snippet of HTML that can be associated with multiple FlatPages.
    '''
    flatpages = models.ManyToManyField(FlatPage, 
        help_text='Select the Flatpages that should display this menu')
    name = models.CharField(max_length=255, 
        help_text='A name for this menu. This is not displayed on the FlatPage.')
    menu = models.TextField(help_text='Enter an HTML snippet for the menu.')

    def __unicode__(self):
        return u"%s"%self.name

# admin.py
from models import FlatpageNav
from django.contrib import admin

class FlatpageNavAdmin(admin.ModelAdmin):
    list_display = ('name', )

admin.site.register(FlatpageNav, FlatpageNavAdmin)

# Then, in your Flatpage default template, add the following:
    {% if flatpage.flatpagenav_set.count %}
        {% for nav in flatpage.flatpagenav_set.all %}
            {{ nav.menu|safe }}
        {% endfor %}
    {% else %}
         {# Include an alternative menu. #}
        {% include "flatpages/menu.html" %}
    {% endif %}
        help_text='A name for this menu. This is not displayed on the FlatPage.')
    menu = models.TextField(help_text='Enter an HTML snippet for the menu.')

    def __unicode__(self):
        return u"%s"%self.name

# admin.py
from models import FlatpageNav
from django.contrib import admin

class FlatpageNavAdmin(admin.ModelAdmin):
    list_display = ('name', )

admin.site.register(FlatpageNav, FlatpageNavAdmin)

# Then, in your Flatpage default template, add the following:
    {% if flatpage.flatpagenav_set.count %}
        {% for nav in flatpage.flatpagenav_set.all %}
            {{ nav.menu|safe }}
        {% endfor %}
    {% else %}
         {# Include an alternative menu. #}
        {% include "flatpages/menu.html" %}
    {% endif %}
Share

Recommended Posts

Leave a Reply

Your email address will not be published. Required fields are marked *