Login

Django Generate Unique Slug

Author:
agusmakmun
Posted:
February 17, 2018
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

Generate unique slug refference by another field.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django.utils.text import slugify


def generate_unique_slug(klass, field, instance=None):
    """
    return unique slug if origin slug is exist.
    eg: `foo-bar` => `foo-bar-1`
    :param `klass` is Class model.
    :param `field` is specific field for title.
    :param `instance` is instance object for excluding specific object.
    """
    origin_slug = slugify(field)
    unique_slug = origin_slug
    numb = 1
    if instance is not None:
        while klass.objects.filter(slug=unique_slug).exclude(id=instance.id).exists():
            unique_slug = '%s-%d' % (origin_slug, numb)
            numb += 1
    else:
        while klass.objects.filter(slug=unique_slug).exists():
            unique_slug = '%s-%d' % (origin_slug, numb)
            numb += 1
    return unique_slug

"""
# USAGE EXAMPLE

from django.db import models
from django.contrib.auth.models import User
from myapp.utils import generate_unique_slug

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)

    def save(self, *args, **kwargs):
        if self.slug:  # edit
            if slugify(self.title) != self.slug:
                self.slug = generate_unique_slug(Post, self.title)
        else:  # create
            self.slug = generate_unique_slug(Post, self.title)
        super(Post, self).save(*args, **kwargs)
"""

More like this

  1. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 weeks, 5 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 1 week ago

Comments

Please login first before commenting.