...

Open source softwares - Django

Back to Course

Lesson Description


Lession - #1009 Django-Variables


Template Variables

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

Example:
template.html:
<h1>Hello {{ firstname }}, how are you?</h1>

Create Variable in View

In Django formats, you can render variables by putting them inside {{ }} brackets:
views.py
from django.http import HttpResponse
from django.template import loader

def testing(request>
: template = loader.get_template('template.html'>
context = { 'firstname': 'Linus', } return HttpResponse(template.render(context, request>
>

Create Variables in Template

You can likewise make variables straightforwardly in the template, by utilizing the {% with %} template tag:
Example:
template.html
{% with firstname="Tobias" %}
<h1>Hello {{ firstname }}, how are you?</h1>

Data From a Model

The model above told a simple methodology on the best way to make and involve variables in a template.

Regularly, a large portion of the external information you need to use in a template, comes from a model.

We have made a model in the past sections, called Members, we will involve this model in the following parts of this instructional exercise.

To get information from the Memebers model, we should import it in the perspectives record, and concentrate information from it in the view:
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Members

def testing(request>
: mymembers = Members.objects.all(>
.values(>
template = loader.get_template('template.html'>
context = { 'mymembers': mymembers, } return HttpResponse(template.render(context, request>
>

Now we can use the data in the template:

template.html
<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>\>
  {% endfor %}
</ul>