Created
September 22, 2017 04:43
-
-
Save agusmakmun/d6fece791e6fcee28ac08dd9c7568a51 to your computer and use it in GitHub Desktop.
Automatically generating unique slugs in Django
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.contrib.auth.models import User | |
from django.utils.text import slugify | |
class Post(models.Model): | |
author = models.ForeignKey( | |
User, related_name='post_author') | |
title = models.CharField(max_length=200) | |
slug = models.SlugField(max_length=200, unique=True) | |
def _unique_slug(self): | |
""" | |
return unique slug if origin slug is exist. | |
eg: `foo-bar` => `foo-bar-1` | |
""" | |
origin_slug = slugify(self.title) | |
unique_slug = origin_slug | |
numb = 1 | |
while Post.objects.filter(slug=unique_slug).exists(): | |
unique_slug = '%s-%d' % (origin_slug, numb) | |
numb += 1 | |
return unique_slug | |
def save(self, *args, **kwargs): | |
if self.slug: # edit mode | |
if slugify(self.title) != self.slug: | |
self.slug = self._unique_slug() | |
else: # create mode | |
self.slug = self._unique_slug() | |
super(Question, self).save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment