Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-MPTT full path to child pages how to make?

I'm start using Django-MPTT app to get a tree-based approach on my Django-site pages.

For ex. I have pages with sub pages:

Trance:

  • Vocal Trance(sub page)
  • Hard Trance(sub page)

Breaks:

  • Atmo Breaks(sub page)
  • Progressive Breaks(sub page)

How can I get access to them from urls.py? What pattern will help? Do I need to store Full_path in model or it can be done via url pattern?

like image 804
Swordfish Avatar asked May 05 '12 09:05

Swordfish


1 Answers

I assume you mean you want to do URLs like this:

/trance/
/trance/vocal-trance/
/trance/hard-trace/
/breaks/
/breaks/atmo-breaks/
/breaks/progressive-breaks/

If so, it's probably best to store the url fragment in your model. Something like:

from mptt.models import MPTTModel
from django.db import models
from django.template.defaultfilters import slugify

class Page(MPTTModel):
    name = models.CharField(max_length=50)
    slug = models.CharField(max_length=50,null=True)
    url = models.CharField(max_length=255,null=True)

    def save(self, *args, **kwargs)
        if self.slug is None:
            # create a slug that's unique to siblings
            slug = slugify(self.name)
            self.slug = slug
            siblings = self.get_siblings()
            i = 1
            while siblings.filter(slug=self.slug).exists():
                i += 1
                self.slug = slug + '-%d' % i

            # now create a URL based on parent's url + slug
            if self.parent:
                self.url = '%s/%s' % (self.parent.url, self.slug)
            else:
                self.url = self.slug
        super(Page, self).save(*args, **kwargs)

Then add a URL pattern:

(r'^pages/(?P<page_url>[\w\d_/-]+)/$', 'pages.views.show_page'),

And in your view you can just fetch the right page:

def show_page(request, page_url=None):
    page = get_object_or_404(Page, url=page_url)
    ...
like image 164
craigds Avatar answered Sep 23 '22 18:09

craigds