Return to Snippet

Revision: 54549
at January 3, 2012 03:36 by chrisaiv


Initial Code
#Things to remember
#django.core.context_processors.auth contains:
#User instance representing the current logged-in user
#Messages tied to a user
#Perms represents permissions the current logged-in user has
#django.core.context_processors.request
#

from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, RequestContext, loader
from django.template.loader import get_template

#
#Lowest Level
#
#Manually loading a template, constructing context, rendering templates
#Does not take advantage of render_to_response()
def view_lowest(request):
    t = loader.get_template("name_of_template.html")
    c = Context({
        "var1": var1,
        "var2": var2,
        "var3": var3
    })
    return t.render(c)
#
#Low Level
#
def custom_processor(request):
    return {
        "var1": var1,
        "var2": var2,
        "var3": var3
    }

def view_lower(request):
    t = loader.get_template("name_of_template.html")
    c = RequestContext(request, {"unique_message": "Specific to a template"},
        processors=[custom_processor])
    return t.render(c)

#
#Normal Level
#
def custom_processor(request):
    return {
        "var1": var1,
        "var2": var2,
        "var3": var3
    }

def view_normal(request):
    return render_to_response("name_of_template.html", {"unique_message": "Specific to a template"},
    context_instance=RequestContext(request, processors=[custom_processor]))

def view_normal2(request):
    return render_to_response("name_of_template.html", {"unique_message": "Specific to a template2"},
    context_instance=RequestContext(request, processors=[custom_processor]))

Initial URL


Initial Description
There are so many ways to serve templates within views.py that sometimes it's hard to get a handle on which is ideal for a project.  This snippet does not attempt to explain every possible way to serve a template, simply a few I've found helpful organized from low-level (more code) to high-level (less code)

Initial Title
Django: 3 ways to serve templates in views.py

Initial Tags
django

Initial Language
Django