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

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.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 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 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.

Django Authentication

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 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.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Django – Sending E-mails

Django – Sending E-mails Django comes with a light engine that is ready and simple to use to send emails. Similar to Python, you just need to import a smtplib. You just need to import django.core.mail in Django. Edit the project settings.py file to start sending emails and set  all the following options: EMAIL_HOST – server with smtp.EMAIL_HOST_USER – smtp server login key.EMAIL_HOST_PASSWORD ? Password credential for the smtp server.EMAIL_PORT – server port smtp.EMAIL_USE_TLS or _SSL – if it is secure connection then set True. Simple E-mail Sending To submit a simple e-mail, let's create it a "simpleEmail" view. from django.core.mail import...

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.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

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.

Django Forms

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. It...

3 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 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 Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 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.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.