Skip to content

Instantly share code, notes, and snippets.

@matheusho
Last active October 13, 2024 00:01
Show Gist options
  • Save matheusho/9258971 to your computer and use it in GitHub Desktop.
Save matheusho/9258971 to your computer and use it in GitHub Desktop.
Django : Generate unique slug
# import signals and slugify
from django.db.models import signals
from django.template.defaultfilters import slugify
class Post(models.Model):
text = models.TextField("Post text")
# function for use in pre_save
def post_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 Post.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(post_pre_save, sender=Post)
@matheusho
Copy link
Author

matheusho commented May 26, 2018

@Radi85 Today I really think the best approach is use a external_id field with last parameter of URL instead the count on post save.

e.g.

urlpatterns = [
    path("<slug:str>-<external_id:str>/", PostDetailView.as_view(), name="detail"),
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment