Users Online

· Guests Online: 38

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Template Tags

Django Template Tags

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 set by 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 %}

To declare the template tags in HTML, the template tag name must be encapsulated within the open and close braces. 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:

Django Template Tags 1

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:

firstof

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/bootstrap@4.5.3/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:

Django Template Tags 3

5. now Tag

The now tag displays the current date and time value. In addition, now tag takes one argument which mentions the format of displaying the date and time.

Example:

Main.html:

{% now "D d M Y" %}

Output:

now

6. lorem Tag

The lorem tag is helpful in setting the sample data for templates. The lorem displays random data in “lorem ipsum” random text.

Example:

Main.html:

{% lorem %}

Output:

lorem

Conclusion

The article depicts how the template tags are placed in Django. First, it clearly shows the syntax of the tags. Next, the syntax and the working process of the syntax are shown. Along then, all the various types of template tags are shown. Finally, each tag is used with suitable code changes, and the output is snapped and placed for reference.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.84 seconds
10,842,666 unique visits