[Fixed]-Using Django view variables inside templates

27👍

In order to have access to a variable in a template, it needs to be in the the context used to render that template. My guess is you aren’t passing a context dictionary to the template when you render it.

http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response

The “dictionary” referenced there is a dictionary that contains all the variables you want to have available in the context. For example:

return render_to_response('your_template.html', {'h': h})

As far as the “no error” error goes… That’s the default setting for an invalid template variable. You can change that in the project’s settings if you’d like.

http://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid

7👍

You can also use

return render(request, 'your_template.html', {'h':h, 'var1':var1})

Refer to the latest manual on https://docs.djangoproject.com/es/1.9/topics/http/shortcuts/

👤Newton

3👍

Yes! This is normal. Such errors in templates fail silently and this is expected in Django.

to render properly template use render_to_response('your_template.html', {'h':h}) (there is also a nasty shortcut render_to_response('your_template.html', locals()) if your context dictionary is very big)

here is some explanation with examples: http://www.djangobook.com/en/beta/chapter04/ (section ‘How invalid variables are handled’)

👤dzida

Leave a comment