Updated May 23, 2023
Introduction to Django Template Tags
The template tags are tags in the template files. These tags help to set dynamic values in the templates. In addition, the template tags are very useful in the type of value it is expected to be populated. These are the key considerations for setting the template tags in Django. The template tags can be placed in both a predefined manner and a built-in manner. Both these techniques allow the setup of template tags in the Django framework within the templates. There are several template tags used.
Syntax:
{% Tag_Name %}
The name must be encapsulated within the open and closed braces to declare the template tags in HTML. So, the content encapsulated within these two tags forms the template tag content. Then the tag expects modulo symbols adjacent to the open and close braces used. This is how the template tags are initiated in Django-based applications.
Types of Template Tags
Given below are the types of template tags:
1. cycle Tag
The cycle tag iterates through all the cycle elements and performs the intended operation.
Example:
Views.py:
def Main_view(request):
list_Var = [1,2]
return render(request,'Main.html',{'list_Var':list_Var})
Main.html:
{% for i in list_Var %}
hello All.............
{% endfor %}
Output:
2. firstof Tag
The firstof the tag prints the first variable with a valid value from a group of variables.
Example:
Views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import NewUserForm,Valueform
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.urls import reverse
def All_users(request):
User_entries = User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
return render(request,"All_users.html",{'users':users})
def Main_view(request):
var1 = ''
var2 = 'Value found in var2'
return render(request,'Main.html',{'var1':var1,'var2':var2})
Main.html:
{% firstof var1 var2 %}
Output:
3. comment Tag
The comment tag ignores all content placed between the tag items.
Example:
Views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import NewUserForm,Valueform
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.urls import reverse
def All_users(request):
User_entries = User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
return render(request,"All_users.html",{'users':users})
def Sign_up_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
print(form.is_valid())
if form.is_valid():
user = form.save()
login(request, user)
print(User.objects.all())
messages.success(request, "Registration successful." )
return redirect("http://127.0.0.1:8000/")
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm
return render (request,template_name="Signup.html", context={"Sign_up_form":form})
{% comment "Hello world" %}
hello All users
{% endcomment %}
def login_request(request):
if request.method == "POST":
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(request,username=username, password=password)
if user is not None:
print('1',request.user.is_authenticated, request.user)
login(request, user)
# logout(request)
print('1',request.user.is_authenticated, request.user)
messages.info(request, f"You are now logged in as {username}.")
return redirect("http://127.0.0.1:8000/")
else:
messages.error(request,"Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form":form})
{% comment "Hello world" %}
hello All users
{% endcomment %}
def logout_request(request):
if request.user.is_authenticated:
logout(request)
print('2',request.user.is_authenticated, request.user)
messages.info(request, "Logged out successfully!")
named_redirect = reverse('Welcome_page')
print(named_redirect)
return redirect(named_redirect)
# return redirect("http://127.0.0.1:8000/")
def Welcome_page(request):
return render(request,'Welcomepage.html')
@login_required
def form_view(request):
form = Valueform(request.POST or None,files=request.FILES)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user stored',request.user)
post.save()
return render(request,'form.html', {"form": form})
{% comment "Hello world" %}
hello All users
{% endcomment %}
4. include Tag
The include tag allows embedding a different HTML page into the current HTML page.
Example:
Main.html:
{% include "test.html" %}
Test.html:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- cropper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css">
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- cropper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css">
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- cropper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css">
<title>Techno-Thoughts</title>
</head>
<body>
{% for i in list %}
hello All users
{% endfor %}
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e)
{
var image = document.getElementById('image');
image.src = URL.createObjectURL(input.files[0]);
}
reader.readAsDataURL(input.files[0]);
var download = document.getElementById('download');
download.src = URL.createObjectURL(input.files[0]);
download.setAttribute("download", 'sample.img');
download.click();
}
}
</script>
<div>
<input type='file' id="input" onchange="readURL(this);" />
<img id="image" alt="your image" />
<br>
<br>
<button id="download" name="download" value="download">download</button>
</div>
</body>
</html>
Output:
5. now Tag
The now tag displays the current date and time value. In addition, now the tag takes one argument which mentions the format of displaying the date and time.
Example:
Main.html:
{% now "D d M Y" %}
Output:
6. lorem Tag
The lorem tag helps set the sample data for templates. The lorem displays random data in “lorem ipsum” random text.
Example:
Main.html:
{% lorem %}
Output:
Conclusion
The article demonstrates the placement of template tags in Django. First, it illustrates the syntax of the tags. Next, it presents the syntax and explains how it works. Then, it showcases different types of template tags. Finally, it utilizes each tag with appropriate code modifications and captures the output for reference.
Recommended Articles
We hope that this EDUCBA information on “Django Template Tags” was beneficial to you. You can view EDUCBA’s recommended articles for more information.