Skip to main content

Conditional Statements

Django's template system provides conditional statements, which fulfill the same objective as in Python code, but in this case whether or not the condition is met determines whether a block of code from the template is displayed or not. For example:

def index(request: HttpRequest) -> HttpResponse:
ctx = {
"name": "John",
"courses": 0
}
return render(request, "myapp/index.html", ctx)

And in the template:

<html>
<strong>Hello</strong>, <em>{{ name }}</em>!
{% if courses > 0 %}
You took {{ courses }} courses.
{% else %}
You haven't taken any courses yet.
{% endif %}
</html>

As expected, if the context variable courses is greater than zero, the first message will be displayed, while if it is zero, “You have not taken any courses yet” will be displayed. Note that the body of a conditional can contain HTML code.