Introduction to Django Framework
Introduction to Django Framework
Characteristics of Django
Here are the main characteristics of Django:
Loosely Coupled- Django helps you to make each element of its stack
independent of the others.
Less code- Ensures effective development
Not repeated- Everything should be developed in precisely one place instead
of repeating it again
Fast development- Django’s offers fast and reliable application development.
Consistent design- Django maintains a clean design and makes it easy to
follow the best web development practices.
Set Virtual environment- Setting up the virtual environment will allow you to
edit the dependency which generally your system wouldn’t allow.
Follow these steps to set up a virtual environment-
Start the server- Start the server by typing following command in cmd-
python [Link] runserver
A Django project contains the following packages and files. The outer
directory is just a container for the application. We can rename it further.
[Link]: This file contains the listed URLs of the application. In this file,
we can mention the URLs and corresponding actions to perform the task and
display the view.
Initially, this project is a default draft which contains all the required
files and folders.
Django provides a built-in admin module which can be used to perform CRUD
operations on the models. It reads metadata from the model to provide a quick
interface where the user can manage the content of the application.
This is a built-in module and designed to perform admin related tasks to the
user.
Let's see how to activate and use Django's admin module (interface).
Django App
In the previous topics, we have seen a procedure to create a Django project.
Now, in this topic, we will create app inside the created project.
Creating an App
To create an app, we can use the following command.
Initially, all the files are empty, no code is available but we can use these
to implement business logic on the basis of the MVC design pattern.
Open [Link] file in any text editor and write the given code to it and do
the same for [Link] file too.
// [Link]
def hello(request):
return HttpResponse("<h2>Hello, Welcome to Django!</h2>")
// [Link]
urlpatterns = [
path('admin/', [Link]),
path('hello/', [Link]),
]
We have made changes in two files of the application. Now, let's run the it
by using the following command. This command will start the server at port
8000.
Method-1
To create a basic app in your Django project you need to go to the directory
containing [Link] and from there enter the command :
The following diagram illustrates how each of the components of the MVT pattern
interacts with each other to serve a user request -
the user. Let's see how to activate and use Django's admin module
(interface).
Django App
In the previous topics, we have seen a procedure to create a Django project. Now, in
this topic, we will create app inside the created project.
Django application consists of project and app, it also generates an automatic base
directory for the app, so we can focus on writing code (business logic) rather than
creating app directories.
The difference between a project and app is, a project is a collection of configuration
files and apps whereas the app is a web application which is written to perform business
logic.
Creating an App
To create an app, we can use the following command.
See the directory structure of the created app, it contains the migrations folder to
store migration files and model to write business logic.
Initially, all the files are empty, no code is available but we can use these to implement
business logic on the basis of the MVC design pattern.
Open [Link] file in any text editor and write the given code to it and do the same for
[Link] file too.
// [Link]
We have made changes in two files of the application. Now, let's run the it by using
the following command. This command will start the server at port 8000.
Open any web browser and enter the URL localhost:8000/hello. It will show the output given below.
Django MVT
The MVT (Model View Template) is a software design pattern. It is a collection of three
important components Model View and Template. The Model helps to handle database.
It is a data access layer which handles the data.
The Template is a presentation layer which handles User Interface part completely. The
View is used to execute the business logic and interact with a model to carry data and
renders a template.
Although Django follows MVC pattern but maintains it?s own conventions. So, control is
handled by the framework itself.
There is no separate controller and complete application is based on Model View and
Template. That?s why it is called MVT application.
See the following graph that shows the MVT based control flow.
Here, a user requests for a resource to the Django, Django works as a controller and
check to the available resource in URL.
If URL maps, a view is called that interact with model and template, it renders a
template. Django responds back to the user and sends a template as a response.
Django Model
In Django, a model is a class which is used to contain essential fields and methods. Each
model class maps to a single table in the database.
The first_name and last_name fields are specified as class attributes and each
attribute maps to a database column.
This model will create a table into the database that looks like below.
The created table contains an auto-created id field. The name of the table is a
combination of app name and model name that can be changed further.
1. INSTALLED_APPS = [
2. #...
3. 'appname',
4. #...
5. ]
Django Model Fields
The fields defined inside the Model class are the columns name of the mapped
table. The fields name should not be python reserve words like clean, save or delete
etc.
FileField(upload_to=None,
max_length=100, **options)
FloatField class FloatField(**options) It is a floating-point number
represented in Python by a
float instance.
Field Options
Each field requires some arguments that are used to set column attributes. For
example, CharField requires mac_length to specify varchar database.
Field Particulars
Options
Choices An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
field.
Default The default value for the field. This can be a value or a callable object.
help_text Extra "help" text to be displayed with the form widget. It's
useful for documentation even if your field isn't used on a form.
We created a model Student that contains the following code in [Link] file.
//[Link]
1. class Student([Link]):
2. first_name = [Link](max_length=20)
3. last_name = [Link](max_length=30)
4. contact = [Link]()
5. email = [Link](max_length=50)
6. age = [Link]()
It will create a table myapp_student. The table structure looks like the below.
Django Views
A view is a place where we put our business logic of the application. The view is a
python function which is used to perform some business logic and return a response to
the user. This response can be the HTML contents of a Web page, or a redirect, or a 404
error.
All the view function are created inside the [Link] file of the Django app.
//[Link]
1. import datetime
2. # Create your views here.
3. from [Link] import HttpResponse
4. def index(request):
5. now = [Link]()
6. html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
7. return HttpResponse(html) # rendering the template in
First, we will import DateTime library that provides a method to get current date
and time and HttpResponse class.
Next, we define a view function index that takes HTTP request and
respond back. View calls when gets mapped with URL in [Link]. For
example
1. path('index/', [Link]),
Output:
Returning Errors
Django provides various built-in error classes that are the subclass of
HttpResponse and use to show error message as HTTP response. Some classes are
listed below.
Class Description
// [Link]
Output:
Django View HTTP Decorators
HTTP Decorators are used to restrict access to view based on the request method.
Syntax
require_http_methods(request_method_list)
//[Link]
This method will execute only if the request is an HTTP GET request.
//[Link]
Output:
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.
Django template engine is used to separate the design from the python code and allows
us to build dynamic web pages.
1. TEMPLATES = [
2. {
3. 'BACKEND': '[Link]',
4. 'DIRS': [[Link](BASE_DIR,'templates')],
5. 'APP_DIRS': True,
6. 'OPTIONS': {
7. 'context_processors': [
8. '[Link].context_processors.debug',
9. '[Link].context_processors.request',
10. '[Link].context_processors.auth',
11. '[Link].context_processors.messages',
12. ],
13. },
14. },
15. ]
First, create a directory templates inside the project app as we did below.
After that create a template [Link] inside the created folder.
Our template [Link] contains the following code.
// [Link]
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.
//[Link]
//[Link]
1. path('index/', [Link]),
1. INSTALLED_APPS = [
2. '[Link]',
3. '[Link]',
4. '[Link]',
5. '[Link]',
6. '[Link]',
7. '[Link]',
8. 'myapp'
9. ]
Run Server
Execute the following command and access the template by entering
localhost:8000/index at the browser.
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
//[Link]
//[Link]
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:
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.
1. {% csrf_token
%} 2.
3. {% if user.is_authenticated %}
4. Hello, {{ [Link] }}.
5. {% endif %}
Let's open the file [Link] of the project and see the what it looks like:
// [Link]
See, Django already has mentioned a URL here for the admin. The path function
takes the first argument as a route of string or regex type.
The view argument is a view function which is used to return a response (template) to the user.
Let's see an example that gets user request and map that route to call specified view
function. Have a look at the steps.
1. Create a function hello in the [Link] file. This function will be mapped from the [Link] file.
// [Link]
// [Link]
In this example, hello will be mapped and call hello function from the views file. It is
called URL mapping.
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.
Play Videox
1. INSTALLED_APPS = [
2. '[Link]',
3. '[Link]',
4. '[Link]',
5. '[Link]',
6. '[Link]',
7. '[Link]',
8. 'myapp'
9. ]
1. STATIC_URL = '/static/'
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.
// [Link]
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 '/[Link]' %}" alt="My image" height="300px" width="700px"/>
10. </body>
11. </html>
//[Link]
1. from [Link] import admin
2. from [Link] import path
3. from myapp import views
4. urlpatterns = [
5. path('admin/', [Link]),
6. path('index/', [Link]),
7. ]
//[Link]
1. def index(request):
2. return render(request,'[Link]')
After that access the template by localhost:8000/index URL, and it will produce the
following output to the browser.
1. {% load static %}
2. <script src="{% static '/js/[Link]' %}"
// [Link]
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/[Link]' %}" type="text/javascript"></script>
8. </head>
9. <body>
10. </body>
11. </html>
// [Link]
After that access the template by localhost:8000/index URL, and it will produce the
following output to the browser.
Django Loading CSS Example
To, load CSS file, use the following code in [Link] file.
1. {% load static %}
2. <link href="{% static 'css/[Link]' %}" rel="stylesheet">
After that create a directory CSS and file [Link] which contains the following code.
// [Link]
1. h1{
2. color:red;
3. }
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/[Link]' %}" rel="stylesheet">
8. </head>
9. <body>
10. <h1>Welcome to Javatpoint</h1>
11. </body>
12. </html>
After that access the template by entering localhost:8000/index URL, and it will produce
the following output to the browser.
Well, in this topic, we have learned the process of managing static files efficiently.
Django automatically does it for us to reduce the application development time. For example, suppose we have a model
containing various fields, we don't need to repeat the fields in the form file.
For this reason, Django provides a helper class which allows us to create a Form class from a
First, create a model that contains fields name and other metadata. It can be used to create a table in database and dynamic HTML form.
// [Link]
This file contains a class that inherits ModelForm and mention the model name for which HTML form is created.
// [Link]
1. from django import forms
2. from [Link] import
Student 3.
4. class EmpForm([Link]):
5. class Meta:
6. model = Student
7. fields = " all "
//[Link]
//[Link]
And finally, create a [Link] file that contains the following code.
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>
Run Server
Run the server by using python [Link] runserver command.
After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.
Output:
Well, an HTML form is created automatically. This is a feature of Django.
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
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.
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.
Commonly used fields and their details are given in the below table.
Let's see a complete example to create an HTML form with the help of Django Form class.
// [Link]
1. from [Link] import render
2. from [Link] import
StudentForm 3.
4. def index(request):
5. student = StudentForm()
6. return render(request,"[Link]",{'form':student})
Passing the context of form into index template that looks like this:
// [Link]
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>
Run Server and access the form at browser by localhost:8000/index, and it will produce the following output.
There are other output options though for the <label>/<input> pairs:
Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns
True if data is valid and place all data into a cleaned_data attribute.
Let's see an example that takes user input and validate input as well.
// [Link]
// [Link]
//[Link]
1. def emp(request):
2. if [Link] == "POST":
3. form = EmployeeForm([Link])
4. if form.is_valid():
5. try:
6. return redirect('/')
7. except:
8. pass
9. else:
10. form = EmployeeForm()
11. return render(request,'[Link]',
// [Link]
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" enctype="multipart/form-data">
9. {% csrf_token %}
10. {{ form.as_p }}
11. <button type="submit" class="save btn btn-default">Save</button>
12. </form>
13. </body>
14. </html>
The [Link]() method is used to create a file input and submit the file to the server. While working with files,
make sure the HTML form tag contains enctype="multipart/form-data" property.
Let's see an example of uploading a file to the server. This example contains the following files.
Template ([Link])
1. <body>
2. <form method="POST" class="post-form" enctype="multipart/form-data">
3. {% csrf_token %}
4. {{ form.as_p }}
5. <button type="submit" class="save btn btn-default">Save</button>
6. </form>
7. </body>
Form ([Link])
View ([Link])
Here, one extra parameter [Link] is required in the constructor. This argument contains the uploaded file instance.
This function is used to read the uploaded file and store at provided location. Put this code into the [Link] file. But
first create this file into the project.
1. def handle_uploaded_file(f):
2. with open('myapp/static/upload/'+[Link], 'wb+') as destination:
3. for chunk in [Link]():
4. [Link](chunk)
Now, create a directory upload to store the uploaded file. Our project structure looks like below.
Initially, this directory is empty. so, let's upload a file to it and later on it will contain the uploaded file.
Start Server
Output
Submit this form and see the upload folder. Now, it contains the uploaded file.
Django Database Connectivity
The [Link] file contains all the project settings along with database connection details. By default, Django works with
SQLite, database and allows configuring for other databases as well.
Database connectivity requires all the connection details such as database name, user credentials, hostname drive name etc.
To connect with MySQL, [Link] driver is used to establishing a connection between application and
database. Let's see an example.
We need to provide all connection details in the settings file. The [Link] file of our project contains the following code for the database.
Play Videox
1. DATABASES = {
2. 'default': {
3. 'ENGINE': '[Link]',
4. 'NAME': 'djangoApp',
5. 'USER':'root',
6. 'PASSWORD':'mysql',
7. 'HOST':'localhost',
8. 'PORT':'3306'
9. }
10. }
After providing details, check the connection using the migrate command.
This command will create tables for admin, auth, contenttypes, and sessions. See the example.
Now, access to the MySQL database and see the database from the list of databases. The created database contains the following tables.
Note: It throws an error if database connectivity fails: [Link]: (1045, "Access denied for user 'root'@'localhost'
(using password: YES)")
Migrating Model
Well, till here, we have learned to connect Django application to the MySQL database. Next, we will see how to create
a table using the model.
Each Django's model is mapped to a table in the database. So after creating a model, we need to migrate it. Let's see
an example. Suppose, we have a model class Employee in the [Link] file that contains the following code.
// [Link]
Django first creates a migration file that contains the details of table structure. To create migration use the following command.
The created migration file is located into migrations folder and contains the following code.
See, a table is present in the database. Well, we have successfully established a connection between our Django
application and MySQL database.
Django provides the various commands that are used to perform migration related tasks. After creating a model, we
can use these commands.
o makemigrations : It is used to create a migration file that contains code for the tabled schema of a model.
o migrate : It creates table according to the schema defined in the migration file.
o sqlmigrate : It is used to show a raw SQL query of the applied migration.
o showmigrations : It lists out all the migrations and their status.
Suppose, we have a model as given below and contains the following attributes.
Model
//[Link]
To create a migration for this model, use the following command. It will create a migration file inside the migration folder.
This migration file contains the code in which a Migration class is created that contains the name and fields of employee table.
Migrations
// 0001_initial.py
After creating a migration, migrate it so that it reflects the database permanently. The migrate command is given below.
Apart from creating a migration, we can see raw SQL query executing behind the applied migration. The sqlmigrate app-name
migration- name is used to get raw SQL query. See an example.
the project.
In Django, by default session stores in the database and also allows file-based and cache based sessions. It is
implemented via a piece of middleware and can be enabled by using the following code.
To set and get the session in views, we can use [Link] and can set multiple times too.
The class [Link] is a base class of all session objects. It contains the following standard methods.
Method Description
contains (key) It checks whether the container contains the particular session
object or not.
Let's see an example in which we will set and get session values. Two functions are defined in the [Link] file.
The first function is used to set and the second is used to get session values.
//[Link]
functions.
// [Link]
Run Server
In Django, by default session stores in the database and also allows file-based and cache based sessions. It is
implemented via a piece of middleware and can be enabled by using the following code.
To set and get the session in views, we can use [Link] and can set multiple times too.
The class [Link] is a base class of all session objects. It contains the following standard methods.
Method Description
contains (key) It checks whether the container contains the particular session
object or not.
Let's see an example in which we will set and get session values. Two functions are defined in the [Link] file.
The first function is used to set and the second is used to get session values.
//[Link]
functions.
// [Link]
Run Server
Let's see an example, here we have a Django project to which we are implementing this feature. A view function getfile() is created.
//
[Link]
import
csv
1.
2. def getfile(request):
3. response = HttpResponse(content_type='text/csv')
4. response['Content-Disposition'] = 'attachment; filename="[Link]"'
5. writer = [Link](response)
6. [Link](['1001', 'John', 'Domil', 'CA'])
7. [Link](['1002', 'Amit', 'Mukharji', 'LA', '"Testing"'])
8. return response
// [Link]
1. path('csv',[Link])
While executing to the browser, it renders a CSV file. See the example.
Apart from static data, we can get CSV from the database too. See, the following example in which we are getting data
from the table by using the Employee model.
Output:
Save the file and open into the text editor that contains the following data.
This data is retrieved from the table employee, a snapshot of the table is shown below
Django PDF
Here, we will learn how to design and generate PDF file using Django view. To generate PDF, we will use ReportLab Python
PDF library that creates customized dynamic PDF.
It is an open source library and can be downloaded easily by using the following command in Ubuntu.
Below is a simple PDF example, in which we are outputting a string message "Hello form javatpoint". This library provides a
canvas and tools that are used to generate customized PDF. See the example.
// [Link]
First, provide MIME (content) type as application/pdf, so that output generates as PDF rather than
HTML, Set Content-Disposition in which provide header as attachment and output file name.
Pass response argument to the canvas and drawstring to write the string after that apply to the save() method and return response.
// [Link]
1. path('pdf',[Link])
Run server and access this view on the browser that creates a pdf file. See the examples.
Output:
A PDF file is generated and ready to download. Download the file and open it, it shows the string message that we wrote.
Apart from it, this library contains the lots of other methods to design and generate PDF dynamically.
Well, we have seen that this library is very useful to create a dynamic CSV file. Now, implement it into Django project when required.
Django with Bootstrap
Bootstrap is a framework which is used to create user interface in web applications. It provides css, js and other tools
that help to create required interface.
following steps.
Visit the official site [Link] to download the bootstrap at local machine. It is a zip file, extract it and see it
contains the two folder.
[Link] a Directory
Create a directory with the name static inside the created app and place the css and jss folders inside it. These folders
contain numerous files, see the screen shot.
[Link] a Template
First create a templates folder inside the app then create a [Link] file to implement (link) the bootstrap css and js files.
load the bootstrap files resides into the static folder. Use the following code.
1. {% load
staticfiles %}
And link the files by providing the file location (source). See the [Link] file.
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Title</title>
6. {% load staticfiles %}
7. <link href="{% static 'css/[Link]' %}" >
8. <script src="{% static '[Link]' %}"></script>
9. <script>alert();</script>
10. </head>
11. <body>
12. </body>
13. </html>
In this template, we have link two files one is [Link] and second is [Link]. Lets see how to use them in
application. Suppose, if we don't use bootstrap, our html login for looks like this:
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>login</title>
6. </head>
7. <body>
8. <form action="/save" method="post">
9. <div class="form-group">
10. <label for="email">Email address:</label>
11. <input type="email" class="form-control" id="email">
12. </div>
13. <div class="form-group">
14. <label for="pwd">Password:</label>
15. <input type="password" class="form-control" id="pwd">
16. </div>
17. <div class="checkbox">
18. <label><input type="checkbox"> Remember me</label>
19. </div>
20. <button type="submit" class="btn btn-primary">Submit</button>
21. </form>
22. </body>
23. </html>
Output:
After loading bootstrap files. Our code look like this:
// [Link]
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>login</title>
6. {% load staticfiles %}
7. <link href="{% static 'css/[Link]' %}" rel="stylesheet">
8. <script src="{% static 'js/[Link]' %}"></script>
9. </head>
10. <body>
11. <form action="/save" method="post">
12. <div class="form-group">
13. <label for="email">Email address:</label>
14. <input type="email" class="form-control" id="email">
15. </div>
16. <div class="form-group">
17. <label for="pwd">Password:</label>
18. <input type="password" class="form-control" id="pwd">
19. </div>
20. <div class="checkbox">
21. <label><input type="checkbox"> Remember me</label>
22. </div>
23. <button type="submit" class="btn btn-primary">Submit</button>
24. </form>
25. </body>
26. </html>
Output:
now, our login form loos much nicer. This is advantage of