2017-01-30 11:16:07 +00:00
|
|
|
|
2016-05-30 19:36:14 +00:00
|
|
|
|
|
|
|
from django.db import models
|
2016-06-10 18:05:36 +00:00
|
|
|
from django.utils import encoding
|
2016-06-10 17:56:58 +00:00
|
|
|
from django.utils.text import slugify
|
2016-05-30 19:36:14 +00:00
|
|
|
|
2016-05-30 19:51:17 +00:00
|
|
|
from utils.models import CreatedUpdatedModel
|
2016-05-30 19:36:14 +00:00
|
|
|
|
|
|
|
|
2016-06-10 18:05:36 +00:00
|
|
|
@encoding.python_2_unicode_compatible
|
2016-05-30 19:36:14 +00:00
|
|
|
class NewsItem(CreatedUpdatedModel):
|
|
|
|
class Meta:
|
|
|
|
ordering = ['-published_at']
|
|
|
|
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
content = models.TextField()
|
2016-12-25 14:52:55 +00:00
|
|
|
published_at = models.DateTimeField(null=True, blank=True)
|
2016-06-10 17:56:58 +00:00
|
|
|
slug = models.SlugField(max_length=255, blank=True)
|
2016-12-25 14:52:55 +00:00
|
|
|
archived = models.BooleanField(default=False)
|
2016-05-30 19:36:14 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.title
|
|
|
|
|
2016-06-10 17:56:58 +00:00
|
|
|
def save(self, **kwargs):
|
2016-12-25 14:52:55 +00:00
|
|
|
if self.published_at:
|
|
|
|
# if this is a new newsitem, or it doesn't have a slug, or the slug is in use on another item, create a new slug
|
|
|
|
if (not self.pk or not self.slug or NewsItem.objects.filter(slug=self.slug).count() > 1):
|
|
|
|
published_at_string = self.published_at.strftime('%Y-%m-%d')
|
|
|
|
base_slug = slugify(self.title)
|
|
|
|
slug = '{}-{}'.format(published_at_string, base_slug)
|
|
|
|
incrementer = 1
|
|
|
|
|
|
|
|
# We have to make sure that the slug won't clash with current slugs
|
|
|
|
while NewsItem.objects.filter(slug=slug).exists():
|
|
|
|
if incrementer == 1:
|
|
|
|
slug = '{}-1'.format(slug)
|
|
|
|
else:
|
|
|
|
slug = '{}-{}'.format(
|
|
|
|
'-'.join(slug.split('-')[:-1]),
|
|
|
|
incrementer
|
|
|
|
)
|
|
|
|
incrementer += 1
|
|
|
|
self.slug = slug
|
2016-06-10 17:56:58 +00:00
|
|
|
|
|
|
|
super(NewsItem, self).save(**kwargs)
|
|
|
|
|