Django Template Variables

Django Template Variables

Template Variables

In Django templates, you can render variables by putting them inside {{ }} brackets:

Example

template.html:

Run Example »


Create Variable in View

The variable firstname in the example above was sent to the template via a view:

views.py:

Run Example »

As you can see in the view above, we create an object named context and fill it with data, and send it as the first parameter in the template.render() function.


Create Variables in Template

You can also create variables directly in the template, by using the {% with %} template tag:

Example

template.html:

Run Example »

You will learn more about template tags in the next chapter.


Data From a Model

The example above showed a easy approach on how to create and use variables in a template.

Normally, most of the external data you want to use in a template, comes from a model.

We have created a model in the previous chapters, called Members, we will use this model in the next chapters of this tutorial.

To get data from the Memebers model, we will have to import it in the views file, and extract data from it in the view:

views.py:

Now we can use the data in the template:

template.html:

Run Example »

We use the Django template tag {% for %} to loop through the members.

You will learn more about template tags in the next chapter.

ArmenianEnglish