Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django view variables inside templates

this is a rather basic question (I'm new to Django) but I'm having trouble using a variable set in my view inside my template. If I initialize a string or list inside my view (i.e. h = "hello") and then attempt to call it inside a template:
{{ h }}
there is neither output nor errors. Similarly, if I try to use a variable inside my template that doesn't exist:

{{ asdfdsadf }}

there is again no error reported. Is this normal? And how can I use my variables within my templates. Thanks!

like image 457
Anon Avatar asked Jun 16 '10 18:06

Anon


People also ask

How do I display variables in Django?

Filters. You can modify variables for display by using filters. Filters look like this: {{ name|lower }} . This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase.

How do I use a variable in a template?

In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable with the <input> element as its value. Refer to a template variable anywhere in the component's template.

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach)


2 Answers

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

like image 146
Josh Wright Avatar answered Oct 06 '22 11:10

Josh Wright


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/

like image 22
Newton Avatar answered Oct 06 '22 09:10

Newton