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:

<h1>Hello {{ firstname }}, how are you?</h1>

Create Variable in View

In Django formats, you can render variables by putting them inside {{ }} brackets:
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:
{% 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:
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Members

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

Now we can use the data in the template:

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