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 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 All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

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

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 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 REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

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

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

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

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

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

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 Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.