- July 27, 2007
- template loader
- -3 (after 7 ratings)
One of the things about Django that has always irked me is that there seems to be no standard facility for just loading a page and displaying it, simply. Yes, there is the flatpages module, but it is primarily designed for loading content from a DB. While you specify a custom template and put in junk values for the DB content, it just feels like extra, unnecessary work.
Thinking about the problem some more, I borrowed from the idea of flatpages and implemented a view that will load an otherwise unmapped template off the filesystem and render it. This is very useful when converting an existing site over. Just copy your files over. No need to map anything in the URL conf or use the admin to add any flatpage entries. Since it'll render the template, too, you can even use tags and what not, so it need not be a static page.
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
Add the following after your URLConf. It is written as it is so that it can be easily added after any definition for serving static media: from www.views import default # Update this as appropriate. # Load the default handler last. This will try to locate any templates # on the file system as a last ditch effort. urlpatterns += patterns('', # Pages to load directly from the file system. (r'^(?P<template_name>.*)$', default), ) Then add the following to your view: from django.template import Context, loader from django.http import HttpResponse, HttpResponseNotFound def default(request, template_name): try: t = loader.get_template(template_name) c = Context() response = HttpResponse(t.render(c)) return response except: return HttpResponseNotFound('Page Not Found')
More like this
- Allow template tags in a Flatpage's content by kylefox 6 years, 12 months ago
- Use MEDIA_URL in flatpages with SSL by gobble 5 years ago
- Use MEDIA_URL in flatpages by robhudson 7 years, 3 months ago
- Cheap direct_to_tempalte patterns by jjdelc 6 years, 7 months ago
- render_as_template template tag by cogat 6 years, 3 months ago