Login

Generate unique slug

Author:
hieunv495
Posted:
January 17, 2018
Language:
Python
Version:
1.8
Score:
0 (after 0 ratings)

generate unique slug

 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
45
46
47
48
49
50
51
52
53
54
from django.db import models
from django.utils.text import slugify
# Create your models here.



def get_unique_slug(value,model,slug_field='slug',max_length=None):
    if max_length is None and hasattr(model._meta.get_field(slug_field),'max_length'):
        max_length = model._meta.get_field(slug_field).max_length
    slug = slugify(value)
    num = 1
    if max_length:
        unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
        while model.objects.filter(** {slug_field: unique_slug}).exists():
            unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
            num += 1
    else:
        unique_slug = '{}-{}'.format(slug, num)
        while model.objects.filter(** {slug_field: unique_slug}).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
    return unique_slug


def fill_unique_slug(instance,value_field,slug_field='slug',max_length=None):
    value = getattr(instance,value_field)
    slug = get_unique_slug(value,instance.__class__,slug_field=slug_field,max_length=max_length)
    setattr(instance,slug_field,slug)


class Post(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    # len =1
    slug = models.SlugField(max_length=1, unique=True, blank=True, editable=False)
    # len =2
    slug2 = models.SlugField(max_length=3,blank=True, editable=False)
    # no len
    slug3 = models.SlugField(blank=True, editable=False)
    # len =4
    slug4 = models.SlugField(blank=True, editable=False)


    def __str__(self):
        return '%s | %s | %s | %s' %(self.slug,self.slug2,self.slug3,self.slug4)

    def save(self, *args, **kwargs):
        fill_unique_slug(self,'name')
        fill_unique_slug(self,'name','slug2',max_length=2)
        fill_unique_slug(self,'name','slug3')
        fill_unique_slug(self,'name','slug4',max_length=4)

        super().save(*args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.