Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are if statements in Django template tags?

Njoku Ifeanyi Gerald


In this shot, we will look at the if statement in a Django template.

A Django template is a text document like HTMLHypertext Markup Language with some added jinja syntax.

jinja syntax is a fast, extensible templating engine that uses special placeholders to write code in a Python framework.


The syntax of the Django template language involves four constructs, which are {{ }} or {% %}.

if statements in Django

In programming, the if statement is used to output data only when it meets specific criteria.

The if statement is used to make decisions based on if the criteria are met in a program.

Example 1

#checking if queryset do exist
{% if  queryset %}
# if the criteria is met, it will display the data
{% else %}
<p> does not exist</p>
{% endfor %}

Example 2

{% for data in queryset %}
# if name attribute exist in data, if yes display the result 
    {% if %}
    <p> {{}}</p>
    {% else %}
    <p> no name </p>
    {% endif %}
{% endfor %}


The class is used to create a model for the database.

from django.db import models
from django.urls import reverse

class CRUD(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):

Now, create a file and name it

The</a> class

This class is used to create an HTML-like form using the Django templating engine.

from django import forms
from .models import CRUD

class CRUDFORM(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={
        "class": "form-control",
        "placeholder": "name"
    class Meta:
        model = CRUD
        fields = [

The</a> class

The</a> file class creates functions or classes that visualize how a route will operate.

from django.shortcuts import redirect, render, get_object_or_404
from .models import CRUD
from .forms import CRUDFORM

def home(request):
    queryset = CRUD.objects.all().order_by('-date')
    context = {
        'queryset': queryset
    return render(request, 'app/base.html', context)

In the codebase app, create a folder and name it “templates.”

Inside the “templates” folder, create another folder and name it “app.” Then, inside the “app” folder, create the “base.html” file.

Here, we see how to use the if statement, using the Django template to create criteria. It only displays data if the criteria are met in the decision-making process.

The base.html file


The</a> file

It is used to create a route.

from django.contrib import admin
from django.urls import path, include
from codebase.views import home

urlpatterns = [
    path('', home, name='home')




Njoku Ifeanyi Gerald

View all Courses

Keep Exploring