Django
Django
Module 1:………………………………………………
Prerequisites
Introduction
History , Features
Installation
Django Project
Django Admin
Interface Django App
Module 2:………………………………………………
Django MVT
Django Model
Django View
Django Template
URL Mapping
Static files Handling
Module 3:………………………………………………….
Model Forms
Django Forms
Form Validation
File Upload
Database Connectivity
Module 4:………………………………………………
Database
Migrations Django
Middleware
Request and
Response Django
Exceptions
Module 5: ………………………………………………….
o Django
o Session
Django Cookie
5. Conclusion……………………………………………………….. 6.
Bibliography……………………………………………………..
Module 1
Prerequisites
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
Django Introduction
Django is a web application framework written in Python programming language. It is based
on MVT (Model View Template) design pattern. The Django is very demanding due to its
rapid development feature. It takes less time to build application after collecting client
requirement.
This framework uses a famous tag line:The web framework for perfectionists with
deadlines.
By using Django, we can build web applications in very less time. Django is designed in
such a manner that it handles much of configure things automatically, so we can focus on
application development only.
Popularity
Django is widely accepted and used by various well-known sites such as:
o Instagram
o Mozilla
o Disqus
o Pinterest
o Bitbucket
oThe Washington Times
Features of Django
o Rapid Development
o Secure
o Scalable
o Fully loaded
o Versatile
o Open Source
o Vast and Supported Community
Django Installation
To install Django, first visit to django official site (https://www.djangoproject.com) and
download django by clicking on the download section. Here, we will see various options to download
The Django.
Django requires pip to start installation. Pip is a package manager system which is used to install and
manage packages written in python. For Python 3.4 and higher versions pip3 is used to manage
packages.
Django Project
To create a Django project, we can use the following command. projectname is the name of Django
application.
A Django project contains the following packages and files. The outer directory is just a container for
the application. We can rename it further.
omanage.py: It is a command-line utility which allows us to interact with the project in various
ways and also used to manage an application that we will see later on in this tutorial.
oA directory (djangpapp) located inside, is the actual application package name. Its name is the
Python package name which we'll need to use to import module inside the application.
o__init__.py: It is an empty file that tells to the Python that this directory should be
considered as a Python package.
osettings.py: This file is used to configure application settings such as database connection,
static files linking etc.
ourls.py: 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.
owsgi.py: It is an entry-point for WSGI-compatible web servers to serve Django project.
Initially, this project is a default draft which contains all the required files and folders.
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).
The admin app (django.contrib.admin) is enabled by default and already added into
INSTALLED_APPS section of the settings file.
To access it at browser use '/admin/' at a local machine like localhost:8000/admin/ and it shows
the following output:
It prompts for login credentials if no password is created yet, use the following command to create
a user.
Create an Admin User
python manage.py createsuperuser
Django App
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.
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 Model is a subclass of django.db.models.Model and each field of the model class represents
a database field (column).
Django provides us a database-abstraction API which allows us to create, retrieve, update and
delete
a record from the mapped table.
Model is defined in Models.py file. This file can contain multiple models.
Let's see an example here, we are creating a model Employee which has two
fields first_name and last_name.
1.
2. from django.db import models
3.
4. class Employee(models.Model):
5. first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
The first_name and last_name fields are specified as class attributes and each attribute maps to a
database column.
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 views.py file of the Django app.
import datetime
1.
# Create your views here.
2.
from django.http import HttpResponse
3.
def index(request):
4.
now = datetime.datetime.now()
5.
html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
6.
return HttpResponse(html) # rendering the template in HttpResponse
7.
Let's step through the code.
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 urls.py. For example
path('index/', views.index),
1.
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': '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 URL Mapping
Well, till here, we have learned to create a model, view, and template. Now, we will learn about the
routing of application.
Since Django is a web application framework, it gets user requests by URL locater and responds back.
To handle URL, django.urls module is used by the framework.
Let's open the file urls.py of the project and see the what it looks like:
// urls.py
The view argument is a view function which is used to return a response (template) to the user.
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.
INSTALLED_APPS = [
1.
'django.contrib.admin',
2.
'django.contrib.auth',
3.
'django.contrib.contenttypes',
4.
'django.contrib.sessions',
5.
'django.contrib.messages',
6.
'django.contrib.staticfiles',
7.
'myapp'
8.
]
9.
2. Define STATIC_URL in settings.py file as given below.
STATIC_URL = '/static/'
1.
3. Load static files in the templates by using the below expression.
{% load static %}
1.
4. Store all images, JavaScript, CSS files in a static folder of the application. First create a
directory static, store the files inside it.
Module 3
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 Django
model.
Django ModelForm Example
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.
// model.py
form is
created.
// form.py
1.
2. from django import forms
3. from myapp.models import Student
4.
class EmpForm(forms.ModelForm):
5.
class Meta:
6.
model = Student
7.
fields = "__all__"
Write a view function to load the ModelForm from forms.py.
//views.py
//urls.py
And finally, create a index.html 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>
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.
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.
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.
// models.py
// forms.py
7.
//views.py
1.def emp(request):
2. if request.method == "POST":
3. form = EmployeeForm(request.POST)
4. if form.is_valid():
5. try:
6. return redirect('/')
7. except:
8. pass
9. else:
10. form = EmployeeForm()
11. return render(request,'index.html',{'form':form})
// 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" 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 forms.FileField() 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.
Template (index.html)
1. <body>
2. <form method="POST" class="post-form" enctype="multipart/form-data">
3. {% csrf_token %}
4. {{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
5.
</form>
6.
</body>
7.
Form (forms.py)
Here, one extra parameter request.FILES 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 functions.py file. But first create this file into the project.
1.def handle_uploaded_file(f):
2. with open('myapp/static/upload/'+f.name, 'wb+') as destination:
3. for chunk in f.chunks():
4. destination.write(chunk)
Database connectivity requires all the connection details such as database name, user credentials,
hostname drive name etc.
e need to provide all connection details in the settings file. The settings.py file of our project contains
the following code for the database.
1.DATABASES = {
2. 'default': {
3. 'ENGINE': 'django.db.backends.mysql',
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.
e need to provide all connection details in the settings file. The settings.py file of our project contains
the following code for the database.
1.DATABASES = {
2. 'default': {
3. 'ENGINE': 'django.db.backends.mysql',
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.
python manage.py migrate
This command will create tables for admin, auth, contenttypes, and sessions.
Module 4
Django provides the various commands that are used to perform migration related tasks. After
creating a model, we can use these commands.
omakemigrations : It is used to create a migration file that contains code for the tabled
schema of a model.
omigrate : It creates table according to the schema defined in the migration file.
osqlmigrate : It is used to show a raw SQL query of the applied migration.
oshowmigrations : It lists out all the migrations and their status.
Suppose, we have a model as given below and contains the following attributes.
Model
//models.py
To create a migration for this model, use the following command. It will create a migration file inside
the migration folder.
1. python manage.py makemigrations
Migrations
// 0001_initial.py
After creating a migration, migrate it so that it reflects the database permanently. The migrate
command is given below.
Django provides various built-in middleware and also allows us to write our own middleware.
See, settings.py file of Django project that contains various middleware, that is used to provides
functionalities to the application. For example, Security Middleware is used to maintain the security of
the application.
// settings.py
1. MIDDLEWARE = [
2. 'django.middleware.security.SecurityMiddleware',
3. 'django.contrib.sessions.middleware.SessionMiddleware',
4. 'django.middleware.common.CommonMiddleware',
5. 'django.middleware.csrf.CsrfViewMiddleware',
6. 'django.contrib.auth.middleware.AuthenticationMiddleware',
7. 'django.contrib.messages.middleware.MessageMiddleware',
8. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
9. ]
1.class FirstMiddleware:
2. def __init__(self, get_response):
3. self.get_response = get_response
4.
5. def __call__(self, request):
6. response = self.get_response(request)
7. return response
__init__(get_response)
It must accept the get_response argument because Django initializes middleware with only it. It calls
only once whereas __call__ executes for each request.
Activating Middleware
To activate middleware, add it to the MIDDLEWARE list of the settings.py file.
1.MIDDLEWARE = [
2. 'django.middleware.security.SecurityMiddleware',
3. 'django.contrib.sessions.middleware.SessionMiddleware',
4. 'django.middleware.common.CommonMiddleware',
5. 'django.middleware.csrf.CsrfViewMiddleware',
6. 'django.contrib.auth.middleware.AuthenticationMiddleware',
7. 'django.contrib.messages.middleware.MessageMiddleware',
8. 'django.middleware.clickjacking.XframeOptionsMiddleware',
9. 'add new created middleware here'
10.]
A Django project does not require middleware, the MIDDLEWARE list can be empty but recommended
that have at least a CommonMiddleware.
Django Request and Response
The client-server architecture includes two major components request and response. The Django
framework uses client-server architecture to implement web applications.
When a client requests for a resource, a HttpRequest object is created and correspond view function is
called that returns HttpResponse object.
To handle request and response, Django provides HttpRequest and HttpResponse classes. Each class
has it?s own attributes and methods.
Django HttpRequest
This class is defined in the django.http module and used to handle the client request.
def methodinfo(request):
1.
return HttpResponse("Http request is: "+request.method)
2.
// urls.py
path('info',views.methodinfo)
1.
Django HttpResponse
This class is a part of django.http module. It is responsible for generating response corresponds to
the request and back to the client.
Django Exceptions
An exception is an abnormal event that leads to program failure. To deal with this situation, Django
uses its own exception classes and supports all core Python exceptions as well.
Django core exceptions classes are defined in django.core.exceptions module. This module contains
the following classes.
Exception Description
AppRegistryNotReady It is raised when attempting to use models before the app loading process.
EmptyResultSet If a query does not return any result, this exception is raised.
MultipleObjectsRetu rne This exception is raised by a query if only one object is expected, but multiple
d objects are returned.
SuspiciousOperation This exception is raised when a user has performed an operation that should be
considered suspicious from a security perspective.
It is raised when a user does not have permission to perform the action
PermissionDenied
requested.
ValidationError It is raised when data validation fails form or model field validation.
Module5
Django Session
A session is a mechanism to store information on the server side during the interaction with the
web application.
In Django, by default session stores in the database and also allows file-based and cache based
sessions.
code. It is implemented via a piece of middleware and can be enabled by using the following
To set and get the session in views, we can use request.session and can set multiple times too.
The class backends.base.SessionBase 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.
//views.py
// urls.py
Run Server
Cookie has its expiry date and time and removes automatically when gets expire. Django provides
built-in methods to set and fetch cookie.
The set_cookie() method is used to set a cookie and get() method is used to get the cookie.
Conclusions
It is naive for an Extension professional to feel that if information is delivered during a learning
activity, the educational mission has been accomplished. The broader mandate that learning
generate change in behavior, practice, or belief requires a much more sophisticated science and
art. In today's information-rich culture, Extension's store of information no longer makes the
organization unique. Rather, Extension's organizational strength and uniqueness lie in the
experience and capability of its professionals to motivate individuals and groups to action.
It is important for Extension educators to develop and field test useful models for program
design and delivery that include behavior change. It is equally important for the models to be
linked to sound educational theory that will be valued by partnering agencies and understood by
the targeted clientele.
The process described in this article accomplished these objectives and resulted in information
that now provides a framework for quality training in a broad range of programming. Further
development of the model has resulted in additional insights with practical application beyond
the scope of this article.
References:-
https://www.geeksforgeeks.org/python-django/
https://www.javatpoint.com
https://www.python.org/
https://www.tutorialspoint/