What are if statements in Django template tags?

Overview

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.

Syntax

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
    {{queryset}}
{% 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 data.name %}
    <p> {{data.name}}</p>
    {% else %}
    <p> no name </p>
    {% endif %}
{% endfor %}

Code

The models.py 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):
return self.name

Now, create a file and name it forms.py.

The forms.py</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 = [
'name'
]

The views.py</a> class

The views.py</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

base.html

The urls.py</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('admin/', admin.site.urls),
path('', home, name='home')
]

Free Resources