Professional Documents
Culture Documents
BY
Jay Vasani
ROLL NO. 201120107036
1
lOMoARcPSD|29108659
ACKNOWLEDGEMENT
While working on this project, their patience and valuable hints helped us in
sailing through the rough seas. They were generous enough to lend us their time,
experience and expertise.
Last but not the least, we are also thankful to all our friends without whose
help this process would have been unexpectedly protracted and the meeting of
deadlines would have been impossible.
Jay Vasani
2
lOMoARcPSD|29108659
TABLE OF CONTENTS
1. Abstract ………….………………………………………… .
2. Introduction of Training……………………………………….
3. Introduction of the Organization..…………………………….
4. Training Details (with topics)………………………………….
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
3
lOMoARcPSD|29108659
Module 5: ………………………………………………….
o Django Session
o Django Cookie
5. Conclusion………………………………………………………..
6. Bibliography……………………………………………………..
4
lOMoARcPSD|29108659
1. ABSTRACT
5
lOMoARcPSD|29108659
2. INTRODUCTION OF TRAINING
The purpose of industrial Training is to provide exposure for the students on practical
engineering fields. Through this exposure, students will have better understanding of engineering
practical in general and sense of frequent and possible problems. This training is part of learning
process. So the exposure that uplifts the knowledge and experience of a student needs to be
properly documented in the form of a report. Through this report, the experience gained can be
delivered to their peers. A properly prepared report can facilitate the presentation of the practical
experience in an orderly, precise and interesting manner.
I have chosen Python Django as my training because it will help me in several ways. I have
chosen my languages course in web development and by having little bit knowledge in this
Subject will help me in carrier growth. During learning this I came to understand much more
concepts of other language.
• An awareness of the need for a professional approach to design and the importance of
good documentation to the finished programs.
• Understandhowtoincludeourlogicina program.
6
lOMoARcPSD|29108659
Description:
BrainyBeam Technologies Pvt Ltd is established in 2009-10. We believe to work with less but
highly qualified and experienced developers. We have small team of 80+ developers. We follow
standard software development process. We are well known for On time delivery of high quality
and secure products.
We follow standard software development process. We are well known for On time delivery of
high quality and secure products. We implement standard security protocols for software
development.
• Android development
• Ios development
• Web development
• Windows development
• IoT development
• Enterprise development
7
lOMoARcPSD|29108659
4. TRAINING CONTENT
Module 1
Prerequisites
Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript
• Python with Django Framework
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.
8
lOMoARcPSD|29108659
History
Django was design and developed by Lawrence journal world in 2003 and publicly released under BSD
license in July 2005. Currently, DSF (Django Software Foundation) maintains its development and
release cycle.
Popularity
Django is widely accepted and used by various well-known sites such as:
o Instagram
o Mozilla
o Disqus
o Pinterest
o Bitbucket
o The 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.
9
lOMoARcPSD|29108659
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.
o manage.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.
o A 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.
o settings.py: This file is used to configure application settings such as database connection,
static files linking etc.
o urls.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.
o wsgi.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.
10
lOMoARcPSD|29108659
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.
11
lOMoARcPSD|29108659
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.
12
lOMoARcPSD|29108659
Module 2
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.
13
lOMoARcPSD|29108659
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.
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.
The first_name and last_name fields are specified as class attributes and each attribute maps to a
database column.
14
lOMoARcPSD|29108659
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.
1. import datetime
2. # Create your views here.
3. from django.http import HttpResponse
4. def index(request):
5. now = datetime.datetime.now()
6. html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
7. return HttpResponse(html) # rendering the template in HttpResponse
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
1. path('index/', views.index),
15
lOMoARcPSD|29108659
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.
16
lOMoARcPSD|29108659
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
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.
17
lOMoARcPSD|29108659
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.
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. ]
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.
18
lOMoARcPSD|29108659
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.
// model.py
This file contains a class that inherits ModelForm and mention the model name for which HTML form is
created.
// form.py
19
lOMoARcPSD|29108659
//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>
20
lOMoARcPSD|29108659
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.
21
lOMoARcPSD|29108659
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
22
lOMoARcPSD|29108659
Instantiate the form, check whether request is post or not. It validate the data by
using is_valid() method.
//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>
23
lOMoARcPSD|29108659
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 }}
5. <button type="submit" class="save btn btn-default">Save</button>
6. </form>
7. </body>
Form (forms.py)
View (views.py)
Here, one extra parameter request.FILES is required in the constructor. This argument contains the
uploaded file instance.
24
lOMoARcPSD|29108659
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)
25
lOMoARcPSD|29108659
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',
26
lOMoARcPSD|29108659
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.
27
lOMoARcPSD|29108659
Module 4
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
//models.py
To create a migration for this model, use the following command. It will create a migration file inside
the migration folder.
28
lOMoARcPSD|29108659
Migrations
// 0001_initial.py
After creating a migration, migrate it so that it reflects the database permanently. The migrate
command is given below.
29
lOMoARcPSD|29108659
Django Middleware
In Django, middleware is a lightweight plugin that processes during request and response execution.
Middleware is used to perform a function in the application. The functions can be a security, session,
csrf protection, authentication etc.
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
30
lOMoARcPSD|29108659
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.
31
lOMoARcPSD|29108659
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.
1. def methodinfo(request):
2. return HttpResponse("Http request is: "+request.method)
// urls.py
1. path('info',views.methodinfo)
Django HttpResponse
32
lOMoARcPSD|29108659
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.
MultipleObjectsReturne 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.
PermissionDenied It is raised when a user does not have permission to perform the action
requested.
33
lOMoARcPSD|29108659
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. 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 request.session and can set multiple times too.
The class backends.base.SessionBase is a base class of all session objects. It contains thefollowing
standard methods.
Method Description
contains (key) It checks whether the container contains the particular session object or not.
34
lOMoARcPSD|29108659
Let's see an example in which we will set and get session values. Two functions are defined in
the views.py file.
//views.py
// urls.py
Run Server
35
lOMoARcPSD|29108659
Django Cookie
A cookie is a small piece of information which is stored in the client browser. It is used to store user's
data in a file permanently (or for the specified time).
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.
36
lOMoARcPSD|29108659
// urls.py
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
37
lOMoARcPSD|29108659
Bibliography
Books:-
Two scoops of Django for 1.11 by Daniel Greenfeld’s and Audrey Greenfield
Lightweight Django by Elman and Mark Lavin
References:-
• https://www.geeksforgeeks.org/python-django/
• https://www.javatpoint.com
• https://www.python.org/
• https://www.tutorialspoint/
38