Django Templating Variables


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

In your

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)
    return context

In user.html:

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

<div class="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 {{ }}
  • 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 }}">{{ }}</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

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