Django Templates & Django Static Files Handling & Django Forms

 Django Templates

Django provides a convenient way to generate dynamic HTML pages by using its template system.

A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

Why Django Template?

In HTML file, we can't write python code because the code is only interpreted by python interpreter not the browser. We know that HTML is a static markup language, while Python is a dynamic programming language.

Django template engine is used to separate the design from the python code and allows us to build dynamic web pages.

Django Template Configuration

To configure the template system, we have to provide some entries in settings.py file.

  1. TEMPLATES = [  
  2.     {  
  3.         'BACKEND''django.template.backends.django.DjangoTemplates',  
  4.         'DIRS': [os.path.join(BASE_DIR,'templates')],  
  5.         'APP_DIRS': True,  
  6.         'OPTIONS': {  
  7.             'context_processors': [  
  8.                 'django.template.context_processors.debug',  
  9.                 'django.template.context_processors.request',  
  10.                 'django.contrib.auth.context_processors.auth',  
  11.                 'django.contrib.messages.context_processors.messages',  
  12.             ],  
  13.         },  
  14.     },  
  15. ]  

Here, we mentioned that our template directory name is templates. By default, DjangoTemplates looks for a templates subdirectory in each of the INSTALLED_APPS.

Django Template Simple Example

First, create a directory templates inside the project app as we did below.

django templates

After that create a template index.html inside the created folder.

django templates 1

Our template index.html contains the following code.

// index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6. </head>  
  7. <body>  
  8. <h2>Welcome to Django!!!</h2>  
  9. </body>  
  10. </html>  

Loading Template

To load the template, call get_template() method as we did below and pass template name.

//views.py

  1. from django.shortcuts import render  
  2. #importing loading from django template  
  3. from django.template import loader  
  4. # Create your views here.  
  5. from django.http import HttpResponse  
  6. def index(request):  
  7.    template = loader.get_template('index.html') # getting our template  
  8.    return HttpResponse(template.render())       # rendering the template in HttpResponse  

Set a URL to access the template from the browser.

//urls.py

  1. path('index/', views.index),  

Register app inside the INSTALLED_APPS

  1. INSTALLED_APPS = [  
  2.     'django.contrib.admin',  
  3.     'django.contrib.auth',  
  4.     'django.contrib.contenttypes',  
  5.     'django.contrib.sessions',  
  6.     'django.contrib.messages',  
  7.     'django.contrib.staticfiles',  
  8.     'myapp'  
  9. ]  

Run Server

Execute the following command and access the template by entering localhost:8000/index at the browser.

  1. $ python3 manage.py runserver  
django templates 2

Django Template Language

Django template uses its own syntax to deal with variable, tags, expressions etc. A template is rendered with a context which is used to get value at a web page. See the examples.

Variables

Variables associated with a context can be accessed by {{}} (double curly braces). For example, a variable name value is rahul. Then the following statement will replace name with its value.

  1. My name is {{name}}.   
  2. My name is rahul  

Django Variable Example

//views.py

  1. from django.shortcuts import render  
  2. #importing loading from django template  
  3. from django.template import loader  
  4. # Create your views here.  
  5. from django.http import HttpResponse  
  6. def index(request):  
  7.     template = loader.get_template('index.html') # getting our template  
  8.     name = {  
  9.         'student':'rahul'  
  10.     }  
  11.     return HttpResponse(template.render(name))       # rendering the template in HttpResponse  

//index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6. </head>  
  7. <body>  
  8. <h2>Welcome to Django!!!</h2>  
  9. <h3>My Name is: {{ student }}</h3>  
  10. </body>  
  11. </html>  

Output:

django templates 3

Tags

In a template, Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an "if" statement or a "for" loop, grab content from a database etc.

Tags are surrounded by {% %} braces. For example.

  1. {% csrf_token %}  
  2.   
  3. {% if user.is_authenticated %}  
  4.     Hello, {{ user.username }}.  
  5. {% endif %}  


Django Static Files Handling

In a web application, apart from business logic and data handling, we also need to handle and manage static resources like CSS, JavaScript, images etc.

It is important to manage these resources so that it does not affect our application performance.

Django deals with it very efficiently and provides a convenient manner to use resources.

The django.contrib.staticfiles module helps to manage them.

Django Static (CSS, JavaScript, images) Configuration

1. Include the django.contrib.staticfiles in INSTALLED_APPS.

  1. INSTALLED_APPS = [  
  2.     'django.contrib.admin',  
  3.     'django.contrib.auth',  
  4.     'django.contrib.contenttypes',  
  5.     'django.contrib.sessions',  
  6.     'django.contrib.messages',  
  7.     'django.contrib.staticfiles',  
  8.     'myapp'  
  9. ]  

2. Define STATIC_URL in settings.py file as given below.

  1. STATIC_URL = '/static/'  

3. Load static files in the templates by using the below expression.

  1. {% load static %}  

4. Store all images, JavaScript, CSS files in a static folder of the application. First create a directory static, store the files inside it.

django static files handling

Our project structure looks like this.

django static files handling 1

Django Image Loading Example

To load an image in a template file, use the code given below.

// index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6.      {% load static %}  
  7. </head>  
  8. <body>  
  9. <img src="{% static '/wallpaper.jpeg' %}" alt="My image" height="300px" width="700px"/>  
  10. </body>  
  11. </html>     

//urls.py

  1. from django.contrib import admin  
  2. from django.urls import path  
  3. from myapp import views  
  4. urlpatterns = [  
  5.     path('admin/', admin.site.urls),  
  6.     path('index/', views.index),  
  7. ]     

//views.py

  1. def index(request):  
  2.     return render(request,'index.html')   

Run the server by using python manage.py runserver command.

After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 2

Django Loading JavaScript

To load JavaScript file, just add the following line of code in index.html file.

  1. {% load static %}  
  2.    <script src="{% static '/js/script.js' %}"      

// index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6.      {% load static %}  
  7.     <script src="{% static '/js/script.js' %}" type="text/javascript"></script>  
  8. </head>  
  9. <body>  
  10. </body>  
  11. </html>  

// script.js

  1. alert("Hello, Welcome to Javatpoint");  

Now, our project structure looks like this:

django static files handling 3

Run the server by using python manage.py runserver command.

After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 4

Django Loading CSS Example

To, load CSS file, use the following code in index.html file.

  1. {% load static %}  
  2. <link href="{% static 'css/style.css' %}" rel="stylesheet">     

After that create a directory CSS and file style.css which contains the following code.

// style.css

  1. h1{  
  2. color:red;  
  3. }     

Our project structure looks like this:

django static files handling 5

// index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6.      {% load static %}  
  7.     <link href="{% static 'css/style.css' %}" rel="stylesheet">  
  8. </head>  
  9. <body>  
  10. <h1>Welcome to Javatpoint</h1>  
  11. </body>  
  12. </html>     

Run the server by using python manage.py runserver command.

After that access the template by entering localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 6

Well, in this topic, we have learned the process of managing static files efficiently.


Django Forms

Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears.

It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.

Each field of the form class map to the HTML form <input> element and each one is a class itself, it manages form data and performs validation while submitting the form.

Lets see an example, in which we are creating some fields too.

  1. from django import forms  
  2. class StudentForm(forms.Form):  
  3.     firstname = forms.CharField(label="Enter first name",max_length=50)  
  4.     lastname  = forms.CharField(label="Enter last name", max_length = 100)  

A StudentForm is created that contains two fields of CharField type. Charfield is a class and used to create an HTML text input component in the form.

The label is used to set HTML label of the component and max_length sets length of an input value.

When rendered, it produces the following HTML to the browser.

  1. <label for="id_firstname">Enter first name:</label>  
  2.  <input type="text" name="firstname" required maxlength="50" id="id_firstname" />  
  3. <label for="id_lastname">Enter last name:</label> <input type="text" name="lastname" required maxlength="100" id="id_lastname" />  

Note: Django Form does not include <form> tags, or a submit button. We'll have to provide those ourselves in the template.

Commonly used fields and their details are given in the below table.

NameClassHTML InputEmpty value
BooleanFieldclass BooleanField(**kwargs)CheckboxInputFalse
CharFieldclass CharField(**kwargs)TextInputWhatever you've given as empty_value.
ChoiceFieldclass ChoiceField(**kwargs)Select'' (an empty string)
DateFieldclass DateField(**kwargs)DateInputNone
DateTimeFieldclass DateTimeField(**kwargs)DateTimeInputNone
DecimalFieldclass DecimalField(**kwargs)NumberInputNone
EmailFieldclass EmailField(**kwargs)EmailInput'' (an empty string)
FileFieldclass FileField(**kwargs)ClearableFileInputNone
ImageFieldclass ImageField(**kwargs)ClearableFileInputNone

Let's see a complete example to create an HTML form with the help of Django Form class.

Building a Form in Django

Suppose we want to create a form to get Student information, use the following code.

  1. from django import forms  
  2. class StudentForm(forms.Form):  
  3.     firstname = forms.CharField(label="Enter first name",max_length=50)  
  4.     lastname  = forms.CharField(label="Enter last name", max_length = 100)  

Put this code into the forms.py file.

Instantiating Form in Django

Now, we need to instantiate the form in views.py file. See, the below code.

// views.py

  1. from django.shortcuts import render  
  2. from myapp.form import StudentForm  
  3.   
  4. def index(request):  
  5.     student = StudentForm()  
  6.     return render(request,"index.html",{'form':student})  

Passing the context of form into index template that looks like this:

// index.html

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index</title>  
  6. </head>  
  7. <body>  
  8. <form method="POST" class="post-form">  
  9.         {% csrf_token %}  
  10.         {{ form.as_p }}  
  11.         <button type="submit" class="save btn btn-default">Save</button>  
  12. </form>  
  13. </body>  
  14. </html>  

Provide the URL in urls.py

  1. from django.contrib import admin  
  2. from django.urls import path  
  3. from myapp import views  
  4. urlpatterns = [  
  5.     path('admin/', admin.site.urls),  
  6.     path('index/', views.index),  
  7. ]  

Run Server and access the form at browser by localhost:8000/index, and it will produce the following output.

django forms localhost index output

There are other output options though for the <label>/<input> pairs:

  • {{ form.as_table }} will render them as table cells wrapped in <tr> tags
  • {{ form.as_p }} will render them wrapped in <p> tags
  • {{ form.as_ul }} will render them wrapped in <li> tags

Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.

Comments