Skip to content

Instantly share code, notes, and snippets.

@spenoir
Created August 14, 2012 14:23
Show Gist options
  • Save spenoir/3349712 to your computer and use it in GitHub Desktop.
Save spenoir/3349712 to your computer and use it in GitHub Desktop.
A Page model that represents a webpage. It uses django-html-field(edited) to allow html content and allows for multiple images to be assigned to a page. Also allows for slug to be none in the case of homepages
from django.conf import settings
from django.db import models
from html_field.db.models import HTMLField
from html_field import html_cleaner
import re
cleaner = html_cleaner.HTMLCleaner(allow_tags=settings.ALLOWED_TAGS)
class Page(models.Model):
""" A page is the overall page that can have child pages but
doesn't have to so can be used for static pages too """
class Meta:
permissions = (
("view_api_page", "Can see page api data"),
)
title = models.CharField(max_length=255, help_text="""
The page title
""")
slug = models.SlugField(unique=True, max_length=255, blank=True, null=True, help_text="""
Where on the site does the page exist
""")
live = models.BooleanField(default=True, help_text="""
Is the page currently live on the site?
""")
template = models.CharField(max_length=255,
help_text="""
Choose which template you would like to use for this page content
""")
weight = models.IntegerField(blank=True,null=True)
parent = models.ForeignKey('Page', blank=True, null=True, related_name='subpages')
content = HTMLField(cleaner, blank=True)
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
if self.slug:
return "/%s/" % self.slug
else:
return "/"
def save(self):
# check for a valid slug
if self.slug:
slug_regex = re.compile('^[-\w]+$')
if re.match(slug_regex, self.slug):
return super(Page, self).save()
else:
raise AttributeError('The slug %s is not valid, please try again' % self.slug)
def img_location(instance, filename):
return 'page_images/story_%d/%s'%(instance.page.id, filename)
class PageImage(models.Model):
"""
An Image that is specific to a Page
"""
page = models.ForeignKey('Page', related_name='images')
credit = models.CharField(max_length=200, blank=True)
caption = models.TextField(blank=True)
image = models.ImageField(upload_to=img_location)
public = models.BooleanField(default=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment