tags:

views:

103

answers:

3

Hi

Learning django & python.

Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all * *.html to the relevant .html file directly?

In general even if it does require a view will I have to write a new line in the url.py file for every page?

A: 

One way to do this would be to write a single custom view that wraps the direct_to_template generic view. The wrapper could accept a parameter and accordingly form the name of the template and pass it to direct_to_template. This way you can route multiple pages with a single URL configuration.

Something like this:

url(r'^foo/(?P<page_name>\w+).html$', 'my_static_wrapper', name = 'my_static_wrapper'),

def my_static_wrapper(request, page_name):
    # form template name and call direct_to_template

That said I suspect that there are better solutions out there though.

Manoj Govindan
+7  A: 

As long as there is some uniquely identifying section in the URL, you will not need to create an entry in urls.py for each direct-template url.

For example, you could say that all urls ending in ".html" are referencing a direct file from the templates.

urlpatterns = patterns('',
    (r'(.+).html$', 'django.views.generic.simple.direct_to_template'),
    # ...
)

Take a look at http://docs.djangoproject.com/en/1.2/ref/generic-views/#django-views-generic-simple-direct-to-template for details.

Peter Shinners
Thanks, wasn't exactly what i needed but this did the trick.('(.+\.html)$', direct_to_template),
Derek Organ
+1  A: 

Write a url which grabs the static pages you're interested in

url(r'^(?P<page_name>about|faq|press|whatever)/$', 'myapp.staticpage', name='static-pages')

The staticpage view function in myapp

from django.views.generic.simple import direct_to_template
from django.http import Http404

def staticpage(request, page_name):
    # Use some exception handling, just to be safe
    try:
        return direct_to_template(request, '%s.html' % (page_name, ))
    except TemplateDoesNotExist:
        raise Http404

Of course, you need to follow a naming convention for your templates, but this pattern can be expanded upon as needed.

brianz