Increase max_length on NewsItem.slug. Autogenerate a slug containing the date and slugified title, taking in account of duplicates.
This commit is contained in:
parent
85d6499667
commit
8b76c4a31a
20
news/migrations/0004_auto_20160610_1743.py
Normal file
20
news/migrations/0004_auto_20160610_1743.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Generated by Django 1.9.6 on 2016-06-10 17:43
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0003_newsitem_slug'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='newsitem',
|
||||
name='slug',
|
||||
field=models.SlugField(max_length=255),
|
||||
),
|
||||
]
|
|
@ -1,6 +1,7 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models
|
||||
from django.utils.text import slugify
|
||||
|
||||
from utils.models import CreatedUpdatedModel
|
||||
from news.managers import NewsItemQuerySet
|
||||
|
@ -14,9 +15,34 @@ class NewsItem(CreatedUpdatedModel):
|
|||
content = models.TextField()
|
||||
public = models.BooleanField(default=False)
|
||||
published_at = models.DateTimeField()
|
||||
slug = models.SlugField()
|
||||
slug = models.SlugField(max_length=255, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
def save(self, **kwargs):
|
||||
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
|
||||
|
||||
super(NewsItem, self).save(**kwargs)
|
||||
|
||||
objects = NewsItemQuerySet.as_manager()
|
||||
|
|
Loading…
Reference in a new issue