3

I am setting up a site that has 'pages' that are always within a parent 'category'. Some pages will have the same title but will reside in a different category. Currently django sluggify always adds numbers to the slugs if the name would be the same:

 foo/help/
 bar/help-1/

Is there a way to get it to output a more intelligent slug so that the slug is unique for the page within the category.

foo/help/
bar/help/
etc/help/
etc/help-1/

I am also thinking of having some pages that are unique for a user in the same way. They would always be accessed as a sub of the user making them unique in that way

Designer023
  • 1,902
  • 1
  • 26
  • 43
  • Here is the link: https://docs.djangoproject.com/en/2.0/ref/models/options/#unique-together. About time you accepted bruno's answer I think. – tread Jan 21 '18 at 12:33
  • If you're looking for restricting other users from accesing someone else profile/page with a slug, add this SameUserOnlyMixin https://stackoverflow.com/questions/37754778/prevent-users-to-access-data-of-another-user-when-typing-the-slug-in-the-url – AnonymousUser Dec 15 '21 at 03:31

1 Answers1

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...

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118