Django Template System

Django Template System

Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model to connect the two.

 Render Function

  It works on three parameters-

  • Request- it is the initial phase or request.
  • The path to the template- This is the direction in the project settings.py variables relative to the TEMPLATE DIRS option.
  • Dictionary of parameters- A dictionary containing all the appropriate variables in the model. This variable can be generated, or all local variable declared in the view can be transferred by locals()

Template Configuration

To configure the template system, we have to provide some entries in settings.py file.
 TEMPLATES = [  
 {  
 'BACKEND': 'django.template.backends.django.DjangoTemplates',   
 'DIRS': 
 ,   [os.path.join(BASE_DIR,'templates')] 
 'APP_DIRS': True,  
 'OPTIONS': {  
 'context_processors': [   
 'django.template.context_processors.debug', 
    'django.template.context_processors.request',  
   'django.contrib.auth.context_processors.auth',  
     'django.contrib.messages.context_processors.messages',  
     ], }, }, ]   

 DTL (Django Template Language)

The template engine of Django offers a mini-language to define the application's user-facing layer.

 Displaying Variable

This seems to be a variable: { { variable}}. The model replaces the variable in the third      parameter of the render function with the variable sent by the view. Let's update our hello.html to reveal the date of today – 

First.html
 html>
   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>
 </html>
 View will change like this. 
 def hello(request):
    today = datetime.datetime.now().date()
    return render(request, "hello.html", {"today" : today}) 

Output

Hello World!!!
 Today is Nov. 21, 2019 

As we have noticed, if the parameter is not a string, Django will use the _str_ method to show it; and we may access an object attribute with the same concept as you do in Python. For example, my parameter would be:{{ today.year}} if we decided to show the date-time.

Filters 

They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.

 Examples   

{{string|truncatewords:30}} – This will truncate the string. It will show only starting 30 words.

{{string|lower}} – It will convert a string into a lower case.

{{string|escape|linebreaks}}- Escape the contents of the string, then turn line breaks into tags.

We can also set a default value for the variable.

Tags

Tags allow the following operations to be performed: if condition, loop, inheritance template, and more.

If Tag

Just like in Python, if, and else in your model, you can use it 

<html>
    <body>
       Hello Django World!!!<p>Today is {{today}}</p>
       We are here 
       {% if today.day == 1 %} 
       the first day of month.
       {% elif today.day == 30 %}
       the last day of the month.
       {% else %}
 I do not remember
       {%endif%}
    </body>
 </html> 

Tag For

Just like ' if ' we've got the ' for ' tag, it works just like in Python does. Let's switch our view to give a list to our template

hello(request):
    today = datetime.datetime.now().date() 
    daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek}) 

Tag displaying list using{{for}}

<html>
    <body>
       Hello Django World!!!<p>Today is {{today}}</p>
       {% if today.day == 1 %}
       the first day of month.
       {% elif today.day == 30 %}
       the last day of the month. 
 {% else %} 
       I not remember.
       {%endif%}
       <p> 
          {% for day in days_of_week %}
          {{day}}
       </p>
       {% endfor %}
    </body>
 </html> 

      

Output

Hello Django World!!!
 Today is Nov. 21, 2019
 I not remember
 Monday           
 Tuesday
 Wednesday
 Thursday
 Friday
 Saturday
 Sunday 

 Block And Extends Tag

Without the inheritance of the template, a template model can not be complete. In other words, when designing your templates, you should have a main template with holes to fill the child's template according to your own needs, as a site may need a special CSS for the selected section area.

Title_template.html
 <html>
    <head>
       <title>
          {% block title %}Title of page{% endblock %}
       </title>
    </head>
    <body> 
       {% block content %}
          Body content
       {% endblock %}
    </body>
 </html> 
 <p>
    {% for day in days_of_week %}
    {{day}}
 </p>
 {% endfor %}
 {% endblock % 

Hello .html

% extends
"main_template.html" %}
 {% block title %}My first Page{% endblock %}
 {% block content %}
 Hello World!!!<p>Today is thursday {{today}}</p>
 We are
 {% if today.day == 1 %} 
 the first day of month.
 {% elif today.day == 30 %}
 the last day of the month.
 {% else %}
 I don't remember
 {%endif%} 

In the above example, we will still get the same result as before when calling /myapplication / hello, but now we reallyy on extend and blocking to refactor our code

We identify frames using the label block in the main template.html. The title block contains the name of the page, and the information block contains the main content of the site. We use extend to inherit from the title_template.html in home.html; then, we fill the above-defined block (content and title).


Related Topics

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.