Source

loutontheweb.co.cc / mcblog / models.py

Full commit
import datetime

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify

from middleware.common import get_request

from markdown import markdown
from mctaggit.managers import TaggableField


class Category(models.Model):
    title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    slug = models.SlugField(unique=True,
                            help_text='Suggested value automatically generated from title. Must be unique.')
    description = models.TextField()

    class Meta:
        ordering = ['title']
        verbose_name_plural = 'Categories'

    def save(self, force_insert=False, force_update=False, using=None):
        if not self.slug:
            self.slug = slugify(self.title)
        return super(Category, self).save(force_insert, force_update, using)

    def get_absolute_url(self):
        return reverse('mcblog-category-detail', kwargs={'slug': self.slug})

    def live_entry_set(self):
        return self.entry_set.filter(status=Entry.STATUS_LIVE)

    def __unicode__(self):
        return self.title


class LiveEntryManager(models.Manager):
    def get_query_set(self):
        return super(LiveEntryManager, self).get_query_set().filter(status=self.model.STATUS_LIVE)


class Entry(models.Model):
    STATUS_LIVE = 1
    STATUS_DRAFT = 2
    STATUS_HIDDEN = 3
    STATUS_CHOICES = (
        (STATUS_LIVE, 'Live'),
        (STATUS_DRAFT, 'Draft'),
        (STATUS_HIDDEN, 'Hidden'),
    )

    title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    excerpt = models.TextField(blank=True)
    body = models.TextField()

    excerpt_html = models.TextField(blank=True, editable=False)
    body_html = models.TextField(blank=True, editable=False)

    slug = models.SlugField(unique=True,
                            help_text='Suggested value automatically generated from title. Must be unique.')
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    author = models.ForeignKey(User, editable=False)
    enable_comments = models.BooleanField(default=True)
    featured = models.BooleanField(default=False)
    status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_LIVE)

    category = models.ForeignKey(Category)
    tags = TaggableField()
    tags_cache = models.CharField(max_length=250, editable=False)

    live = LiveEntryManager()
    objects = models.Manager()

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = 'Entries'

    def save(self, force_insert=False, force_update=False, using=None, data_changed=True):
        if data_changed:
            if not self.slug:
                self.slug = slugify(self.title)
            self.body_html = markdown(self.body)
            if self.excerpt:
                self.excerpt_html = markdown(self.excerpt)
        return super(Entry, self).save(force_insert, force_update, using)

    @models.permalink
    def get_absolute_url(self):
        return ('mcblog-entry-detail', (), {'category_slug': self.category.slug,
                                            'slug': self.slug})

    @models.permalink
    def get_arhive_year_url(self):
        return ('mcblog-entry-archive-year', (), {'year': self.pub_date.strftime('%Y')})

    @models.permalink
    def get_arhive_month_url(self):
        return ('mcblog-entry-archive-month', (), {'year': self.pub_date.strftime('%Y'),
                                                  'month': self.pub_date.strftime('%b').lower()})

    @models.permalink
    def get_arhive_day_url(self):
        return ('mcblog-entry-archive-day', (), {'year': self.pub_date.strftime('%Y'),
                                                  'month': self.pub_date.strftime('%b').lower(),
                                                  'day': self.pub_date.strftime('%d')})

    def __unicode__(self):
        return self.title


class Link(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    url = models.URLField(unique=True)
    via_name = models.CharField('Via', blank=True, max_length=250,
                                help_text='The name of the person whose site you spotted the link on. Optional.')
    via_url = models.URLField('Via URL', blank=True,
                              help_text='The url of the site where you spotted the link. Optional.')

    description_html = models.TextField(editable=False)

    slug = models.SlugField(unique_for_date='pub_date',
                            help_text='Suggested value automatically generated from title. Must be unique.')
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    posted_by = models.ForeignKey(User, editable=False)
    enable_comments = models.BooleanField(default=True)
    post_in_blog = models.BooleanField(default=True)

    tags = TaggableField()
    tags_cache = models.CharField(max_length=250, editable=False)

    class Meta:
        ordering = ['-pub_date']

    def save(self, force_insert=False, force_update=False, using=None, data_changed=True):
        if data_changed:
            self.description_html = markdown(self.description)
        return super(Link, self).save(force_insert, force_update, using)

    @models.permalink
    def get_absolute_url(self):
        return ('mcblog-link-detail', (), {'year': self.pub_date.strftime('%Y'),
                                           'month': self.pub_date.strftime('%b').lower(),
                                           'day': self.pub_date.strftime('%d'),
                                           'slug': self.slug})

    def __unicode__(self):
        return self.title


from django.conf import settings
from django.contrib.comments.moderation import CommentModerator, moderator
from django.contrib.sites.models import Site
from akismet import Akismet


class EntryModerator(CommentModerator):
    auto_moderate_field = 'pub_date'
    moderate_after = 30
    email_notification = True

    def moderate(self, comment, content_object, request):
        already_moderated = super(EntryModerator, self).moderate(comment, content_object, request)
        if already_moderated:
            return already_moderated
        akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                              blog_url='http://%s/' % Site.objects.get_current().domain)
        if akismet_api.verify_key():
            akismet_data = {'comment_type': 'comment',
                            'referrer': request.META['HTTP_REFERER'],
                            'user_ip': comment.ip_address,
                            'user_agent': request.META['HTTP_USER_AGENT']}
            return akismet_api.comment_check(comment, akismet_data, build_data=True)
        return False

moderator.register(Entry, EntryModerator)