For this site I have a large number of static pages. Django provides two ways of serving such content: flatpages and the generic view direct_to_template. I prefer the direct_to_template system, but it gets a bit overwhelming when you have a lot pages. I didn't want to define a url pattern for each page, so I wrote a system to handle it. With this system I never have to write a single url pattern, or even an explicit URL.

First we add to our urls.py the pattern:

(r'^(?P<page>.+?)/(?P<path>.*?)/?$', 'website.site.views.static_page')

Now we define the actual view; take note this depends on a dictionary of lists called pages:

def static_page(request, path, page):
     if not path and page in pages:
         template = ''.join((page,"/index.html"))
    elif page in pages and path in pages[page]:
        template = ''.join((page, "/", path, ".html"))
    else:
        raise Http404
    return render_to_response(template, {},
            context_instance=RequestContext(request))

So this code takes the page and path and determines if they exist (as defined in the pages dictionary), and then renders a template which is either page/index.html or page/path.html. Multiple levels are supported, and would be expanded in path. So in the case of a pages dictionary like:

pages = {'oggify': ('development', 'osx'),
        'about': ()}

This defines the following URLs:

/oggify/
/oggify/development/
/oggify/osx/
/about/

I'd have a templates directory that looks like:

templates/
    oggify/
        index.html
        development.html
        osx.html
   about/
        index.html

We could easily extend this system with more context, or page dependent context with very little effort.

Posted: May 10, 2007 | Tags: django python

Comments are closed.

Tags

42 | django | python | oggify | OSCON | OSCON07 | osx | utosc | mythtv | security | reading | music | gaming | programming | tips | shell | vim | pyobjc | cocoa | iphone | blog | git

Calendar

<< May >>
Mo Tu We Th Fr Sa Su
30 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 26 27
28 29 30 31 1 2 3

Search

This space reserved for a search box

RSS Feeds

A Django site. Hosted on a Slicehost Slice