Django Variables


Example

Variables you have provided in your view context can be accessed using double-brace notation:

In your views.py:

class UserView(TemplateView):
  """ Supply the request user object to the template """

  template_name = "user.html"

  def get_context_data(self, **kwargs):
    context = super(UserView, self).get_context_data(**kwargs)
    context.update(user=self.request.user)
    return context

In user.html:

<h1>{{ user.username }}</h1>

<div class="email">{{ user.email }}</div>

The dot notation will access:

  • properties of the object, e.g. user.username will be {{ user.username }}
  • dictionary lookups, e.g. request.GET["search"] will be {{ request.GET.search }}
  • methods with no arguments, e.g. users.count() will be {{ user.count }}

Template variables cannot access methods that take arguments.

Variables can also be tested and looped over:

{% if user.is_authenticated %}
  {% for item in menu %}
    <li><a href="{{ item.url }}">{{ item.name }}</a></li>
  {% endfor %}
{% else %}
  <li><a href="{% url 'login' %}">Login</a>
{% endif %}

URLs are accessed using {% url 'name' %} format, where the names correspond to names in your urls.py.

{% url 'login' %} - Will probably render as /accounts/login/
{% url 'user_profile' user.id %} - Arguments for URLs are supplied in order
{% url next %} - URLs can be variables