Last active
August 1, 2018 14:22
-
-
Save matheusho/9258971 to your computer and use it in GitHub Desktop.
Django : Generate unique slug
This file contains 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
# import signals and slugify | |
from django.db.models import signals | |
from django.template.defaultfilters import slugify | |
# function for use in pre_save | |
def yourmodel_pre_save(signal, instance, sender, **kwargs): | |
if not instance.slug: | |
slug = slugify(instance.attribute) # change the attibute to the field that would be used as a slug | |
new_slug = slug | |
count = 0 | |
while YourModel.objects.filter(slug=new_slug).exclude(id=instance.id).count() > 0: | |
count += 1 | |
new_slug = '{slug}-{count}'.format(slug=slug, count=count) | |
instance.slug = new_slug | |
# Execute signals pre_save | |
signals.pre_save.connect(your_model_pre_save, sender=YourModel) |
Thanks @Alir3z4
thanks but how can i use it ??
this method can be useful when adding only one more similar slug because the count variable will be always 1 since it will be reset to 0 whenever the method is invoked.
You will face race condition when you have 3 similar attribute (instance.attribute).
@Radi85 Today I really think the best approach is use the primary_key
instead count on post save.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice and simple <3