Created
July 25, 2017 22:23
-
-
Save busla/4009a8e5d2ac1587bb068afabe140cdb to your computer and use it in GitHub Desktop.
Django unique slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.urls import reverse | |
from unidecode import unidecode #pip install unidecode | |
from django.utils.crypto import get_random_string | |
from django.utils.text import slugify | |
from taggit.managers import TaggableManager | |
class Blog(models.Model): | |
title = models.CharField(max_length=256) | |
slug = models.SlugField(max_length=256, unique=True) | |
body = models.TextField(null=True, blank=True) | |
created = models.DateTimeField() | |
publish = models.BooleanField(default=False) | |
image = models.ImageField(upload_to='uploads/', null=True, blank=True) | |
tags = TaggableManager() | |
def get_absolute_url(self): | |
return reverse('blog-detail', kwargs={'slug': self.slug}) | |
def _uniquify(self): | |
slug = slugify(unidecode(self.title)) | |
num = len(Blog.objects.filter(slug=slug)) | |
unique_slug = '{}-{}'.format(slug, num+1) if num > 0 else slug | |
return unique_slug | |
def save(self, *args, **kwargs): | |
self.slug = self._uniquify() | |
super(Blog, self).save(*args, **kwargs) | |
def __str__(self): | |
return self.title | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment