Django Template Tags Cheat Sheet

Basic Django Template Tags Cheat Sheet

Download as .pdf

API: /api/v1/cheatsheet/django-template-tags-cheat-sheet

Variables vs Tags

Variables

{{ variable }}

Output data into HTML.

Example:

html

1
{{ post.title }}

If the variable inside {{}} is a Python dict, you can access its elements using:

html

1
{{ variable.key }}

If the variable inside {{}} is a Python list, you can access its elements by index using:

html

1
{{ variable.0 }}

Nested elements:

html

1
{{ variable.key.0 }}

Template Tags

{% tag %}

Used for logic / actions.

Core Template Tags

Load Static Files

html

1
{% load static %}

Required before using static paths.

html

1
<link rel="stylesheet" href="{% static 'css/main.css' %}">

URL Generation

html

1
{% url 'blog:index' %}

Dynamic URL from urls.py

With parameters:

html

1
{% url 'blog:post' post.slug %}

Named arguments:

html

1
{% url 'blog:post' slug=post.slug %}

If Statements

html

1
2
3
4
5
{% if user.is_authenticated %}

    <p>Logged in</p>

{% endif %}

With elif else:

html

1
2
3
4
{% if posts %}
{% elif other_posts %}
{% else %}
{% endif %}

For Loops

html

1
2
3
4
5
{% for post in posts %}

    {{ post.title }}

{% endfor %}

Loop counter: {{ forloop.counter }} -> counter starting at 1 {{ forloop.counter0 }} -> counter starting at 0

Block Inheritance

Inside Base Template:

html

1
2
{% block content %}
{% endblock %}

Inside Child Template:

html

1
2
3
4
5
6
7
{% extends 'base.html' %}

{% block content %}

    <h1>Hello</h1>

{% endblock %}

Include Other Templates

html

1
{% include 'partials/nav.html' %}

Reusable components.

CSRF Protection

Inside POST forms:

html

1
{% csrf_token %}

Required for Django form security.

Common Filters (with variables)

Filters modify output.

Syntax:

html

1
{{ value|filter }}

Examples:

  • {{ name|upper }}
  • {{ text|truncatechars:50 }}
  • {{ content|safe }}
  • {{ date|date:"Y-m-d" }}

Useful Examples:

Auth Navigation

html

1
2
3
4
5
{% if user.is_authenticated %}
    Logout
{% else %}
    Login
{% endif %}

Empty Loop Fallback

html

1
2
3
4
{% for post in posts %}
{% empty %}
<p>No posts found.</p>
{% endfor %}

Join the Newsletter

Practical insights on Django, backend systems, deployment, architecture, and real-world development — delivered without noise.

Get updates when new guides, learning paths, cheat sheets, and field notes are published.

No spam. Unsubscribe anytime.



There is no third-party involved so don't worry - we won't share your details with anyone.