Skip to content

Instantly share code, notes, and snippets.

@teror4uks
Created January 18, 2018 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teror4uks/9758dbafe8b129a53d184fb450215cb5 to your computer and use it in GitHub Desktop.
Save teror4uks/9758dbafe8b129a53d184fb450215cb5 to your computer and use it in GitHub Desktop.
"""From https://fazle.me/auto-generating-unique-slug-in-django/"""
from django.db import models
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=140, unique=True)
content = models.TextField()
def __str__(self):
return self.title
def _get_unique_slug(self):
slug = slugify(self.title)
unique_slug = slug
num = 1
while Article.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
return unique_slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self._get_unique_slug()
super().save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment