Template in views and loading

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:

  1. A template loader is used to locate the actual template to use and parses it into a Template object suitale for rendering.
  2. Context of some sort is instantiated to provide the Template some variables to work with.
  3. The Template is rendered (via its render() method) using the Context.

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>.*)

, 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’)

Template tags and filters
Interacting with a Database: Models

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?