[Django]-Django variables from templates to views – best practice

2👍

A middle way is to use the context dictionary itself as a stack.

context = {}
if <condition>:
    context['cond1'] = 'foo'

if <condition2>:
    context['cond2'] = 'bar'

return render_to_response('template.html', context)

(Also note that since Django 1.3 you can use render(request, template, context) instead of the longwinded context_instance=RequestContext stuff.)

2👍

Either build your context conditionally, i.e.:

context = { 'some_list': some_list }

...

if <something>:
    context['some_variable'] = some_variable

...

return render_to_response('mytemplate.html', context, context_instance=RequestContext(request)    

Or use sensible defaults:

return render_to_response('mytemplate.html', {
    'some_variable' : some_variable or 'Default',
    'some_list': some_list,
}, context_instance=RequestContext(request))

Leave a comment