Certify and Increase Opportunity.
Be
Govt. Certified Django Developer
Template in views and loading
The long way
If you’ve ever read through the Django tutorial, you know that manually loading and rendering a template is a bit of a chore, because it involves multiple separate steps. The canonical example looks like this:
from django.template import loader, Context t = loader.get_template('my_template.html') c = Context({ 'object_list': SomeModel.objects.all() }) rendered = t.render(c)
This shows off all of the steps involved:
- A template loader is used to locate the actual template to use and parses it into a
Template
object suitale for rendering. - A
Context
of some sort is instantiated to provide theTemplate
some variables to work with. - The
Template
is rendered (via itsrender()
method) using theContext
.
Default Template Loading
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>.*) |
Apply for Django Certification Now!!
http://www.vskills.in/certification/Certified-Django-Developer
, 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’)
Apply for Django Certification Now!!
http://www.vskills.in/certification/Certified-Django-Developer