Search code examples
pythondjangourlslugdjango-contenttypes

Django single slug table and nested urls without prefix


Ok so here is my (seemingly unique) problem:

I am trying to get a single slug table working for Django. After countless hours of researching I found out this was not a common problem as I tought. Note: I am relativly new to Django.

The real problem I'm trying to solve

I want a nested slug based url without prefixes, like so:

www.example.com/category-name/product-name

but also:

www.example.com/category-name/brand-name

and so on...

There should be the possibility for a slug history so old slugs kan be redirected.

What I have come up with so far:

  • Making a single slug table for all slugs to ensure they are globally unique
  • Using django-conttenttypes as relation to Models to figure out what views to load
  • Make relations within te slug table to define what should be nested and what not
    • Figure out some way to do a slug table lookup in urls.py to check if url is valid and select the correct view.

I found a Rails gem that does mostly what I want: Friendly_Id

Obviously I am making some basic design mistakes. Can someone point me in the right direction?


Solution

  • Ok, so this question turned out to be more difficult and unique than I tought. For future reference, this is how I eventually solved the problem:

    • Make 1 slug table where all slugs are unique.
    • Use Django ContenType to make generic relations between the slug in the slug table and the entity it belongs to.
    • Made a middleware request rewriter that rewrites the segments of an slug based url to an non slug url, like so: test.com/category-slug/product-slug to test.com/category/6/product/12, using the generic relation.
    • Use the rewritten url internally in Django

    Note: This approach requires all slugs the be unique globally, so all the segments of the url are unique, which is a bit of a pain, but is doable.