[Django]-Is is possible to have the Django slugfield unique per user or other model

5đź‘Ť

The slugify function itself (django.template.defaultfilters.slugify) only works on it’s input so that’s not what gets you such result.

wrt/ your original question, ie “Is it possible to have a slugfield unique per user or other model”, it’s just a matter of declaring the relevant fields as unique_together in your model’s Meta, ie

class Category(models.Model):
    # code here

class Page(models.Model):
    category = models.ForeignKey(Category)
    slug = models.SlugField("slug")

    class Meta:
        unique_together = (
            ("category", "slug"), 
        ) 

Then if you have some code that autogenerate / prepopulate the slug field you’ll have to tweak it manually to take care of the category…

Leave a comment