Login

Hierarchical page slugs

Author:
baumer1122
Posted:
August 10, 2007
Language:
Python
Version:
.96
Tags:
slug url
Score:
2 (after 2 ratings)

This allows for urls in the form of /grandparent-slug/parent-slug/self-slug/ where the number of parent slugs could be 0 to many.

You'll need to make sure that it is your last urlpattern because it is basically a catch-all that would supersede any other urlpatterns.

Assumes your page model has these two fields:

  • slug = models.SlugField(prepopulate_from=("title",), unique=True)
  • parent = models.ForeignKey("self", blank=True, null=True)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
### last item in urlpatterns in urls.py
(r'^(?P<full_slug>(.*))/$', 'myproject.myapp.views.pages')


### myview
from django.http import Http404
from django.shortcuts import get_object_or_404

def pages(request, full_slug):
    slugs = full_slug.split('/')
    page_slug = slugs[-1]
    page = get_object_or_404(Page,slug=page_slug)
    if not page.get_absolute_url().strip('/') == full_slug:
       raise Http404
    ### if you reach this line, you've found the page


### in page model
    def get_absolute_url(self):
        url = "/%s/" % self.slug
        page = self
        while page.parent:
            url = "/%s%s" % (page.parent.slug,url)
            page = page.parent
        return url

More like this

  1. Recurse template tag for Django by Zarin 7 years, 1 month ago
  2. Pagination Alphabetically compatible with paginator_class by vascop 2 years, 11 months ago
  3. @url decorator - getting rid of urlpatterns by southern_sun 7 years, 7 months ago
  4. Self-referencing Foreign Key Infinite Loop by minarets 7 years, 6 months ago
  5. direct to template from a subdir by Scanner 6 years, 5 months ago

Comments

imakethings (on August 25, 2007):

Would it be possible to show all the children of a parent? For example:

/about/ -- /about/tom/ -- /about/richard/ -- /about/jane/ ---- /about/jane/hobbies/ ---- /about/jane/education/

What would be the best to approach this extraction?

#

imakethings (on August 25, 2007):

Someone in the IRC #django mentioned this:

obj.page_set.all()

#

imakethings (on August 27, 2007):

How would you pull the data out from the view to the template?

#

Please login first before commenting.