Django development - how to access model results correctly
Ok forgive me if this is a bit of a noddy question but i can't find a example online. I'm a PHP dev converting to Django from Codeigniter. I'm calling a model i have made like thus;
if request.method == 'GET':
for e in Ratecard.objects.filter(reportSuite=region):
suite = e.reportSuite
开发者_开发知识库 RP_UniqueUsers = e.RP_UniqueUsers
RP_PageImpressions = e.RP_PageImpressions
RP_TimeSpent = e.RP_TimeSpent
RP_PageViewPerVisit = e.RP_PageViewPerVisit
HP_PageImpressions = e.HP_PageImpressions
HP_UniqueUsers = e.HP_UniqueUsers
HP_TimeSpent = e.HP_TimeSpents
return render_to_response('rates.html', locals())
In this example 'region' is set from a GET param. My problem is that if i then try to access suite from my template i get nothing out of it. {{ region }} doesn't print any result.
What is the correct way of accessing this data both in the view and in the template?
Your local view variables are not visible in your templates by default. You have to pass them explicitly in a context dictionary. Usually you will do this in render_to_response
.
Example:
def index(request):
# a local variable
region = "sanriku"
# render_to_response takes a template file name as the first argument
# and optionally some more parameters, such as a context dictionary,
# that holds your variables, which will be accessible in this view.
# Here, e.g. the variable {{ region }} will be accessible and will print
# just "sanriku".
return render_to_response("index.html", {"region" : region})
Django 1.3 introduced a new shortcut render
:
render() is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.
A shortcut to any GET request parameter would be:
{{ request.GET.q }}
if you have a request context processor enabled.
Just for development purposes: If you want to save some keystrokes during development, you can add all local variables at once via the locals()
function, which returns a dictionary representing the current local symbol table. So the most dense way to have access to all local variables in your template as well as all data the RequestContext contains, you could write:
# Django 1.3
return render("template.html", **locals())
# Pre Django 1.3
return render("template.html", **locals(),
context_instance=RequestContext(request))
精彩评论