我意识到使用:
...
return render_to_response('mytemplate.html',
locals(), context_instance=RequestContext(request))
视图中的不被认为是好的代码,例如:
...
return render_to_response('mytemplate.html', {
'some_variable' : some_variable,
'some_list': some_list,
}, context_instance=RequestContext(request))
因其易读性和明确性而被认为更好。我只是好奇如何处理可能会或可能不会返回的变量。我应该在这样的视图中明确设置它们:
...
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))
会导致更长的视图代码。或者我应该在将变量包含在响应中之前检查变量是否存在?
当然,如果我什么也不做,那么我得到:
local variable 'some_variable' referenced before assignment
欢迎任何建议。
答案 0 :(得分:2)
中间方法是将上下文字典本身用作堆栈。
context = {}
if <condition>:
context['cond1'] = 'foo'
if <condition2>:
context['cond2'] = 'bar'
return render_to_response('template.html', context)
(另请注意,自Django 1.3起,您可以使用render(request, template, context)
代替longwinded context_instance=RequestContext
内容。)
答案 1 :(得分:2)
有条件地构建你的上下文,即:
context = { 'some_list': some_list }
...
if <something>:
context['some_variable'] = some_variable
...
return render_to_response('mytemplate.html', context, context_instance=RequestContext(request)
或使用合理的默认值:
return render_to_response('mytemplate.html', {
'some_variable' : some_variable or 'Default',
'some_list': some_list,
}, context_instance=RequestContext(request))