Hi,
render_to_response
Is it possible to pass more variables than just one? For example in my application I have a members model and then i would like to display the members information and also attendance information. Would I have to supply the arguments as a tuple?
Thanks in Advance,
Dean
views:
42answers:
2Render_to_response
accepts a context which is used for rendering. As far as I know there is no limitation on the number of variables you can pass in the context. This includes QuerySets. For example:
def my_view(request, *args, **kwargs):
# ... etc ...
q1 = Model1.objects.filter(**conditions)
q2 = Model2.objects.filter(**conditions)
context = dict(q1 = q1, q2 = q2)
return render_to_response('my_template.html', context_instance = RequestContext(request, context))
My example uses RequestContext
but it should be fine without it too.
# Template
{% for foo in q1 %} {{ foo }} {% endfor %}
... stuff ...
{% for bar in q2 %} {{ bar }} {% endfor %}
While Manoj is correct that you can pass variables by constructing your own context instance and passing it as a keyword argument to render_to_response, it's often shorter/simpler to use the second positional argument to render_to_response which accepts a dictionary that gets added to the context behind the scenes.
Take a quick look at the docs for render_to_response. Their example usage looks like this (and allows you to pass anything that can be stored in a dict to the renderer):
from django.shortcuts import render_to_response
def my_view(request):
# View code here...
return render_to_response('myapp/index.html', {"foo": "bar"},
mimetype="application/xhtml+xml")