I realize that using:
...
return render_to_response('mytemplate.html',
locals(), context_instance=RequestContext(request))
in views is not considered good code and something like:
...
return render_to_response('mytemplate.html', {
'some_variable' : some_variable,
'some_list': some_list,
}, context_instance=RequestContext(request))
is considered better for its legibility and explicitness. I was just curious how best to deal with variables which may or may not be returned. Should I explicitly set them in the views like this:
...
some_variable = None
some_variable = <some business logic>
return render_to_response('mytemplate.html', {
'some_variable' : some_variable,
'some_list': some_list,
}, context_instance=RequestContext(request))
which would result in more lengthy view code. Or should I check for existence of the variables before including them in the response?
Of course if I do nothing then I get:
local variable 'some_variable' referenced before assignment
Any suggestions welcomed.
A middle way is to use the context dictionary itself as a stack.
(Also note that since Django 1.3 you can use
render(request, template, context)instead of the longwindedcontext_instance=RequestContextstuff.)