Django-Training-Report - Chirag
Django-Training-Report - Chirag
Django-Training-Report - Chirag
PYTHON DJANGO
BY
Chirag Kathpalia
Reg. No: (191380195)
ACKNOWLEDGEMENT
It is with the great sense of satisfaction that we present our reveal venture in
training process in the form of project work. We are very fortunate to have Mr.
Chandra Prakash as our trainee and mentor.
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.
We also acknowledge, with great thanks, our Head of the Centre and Program
Coordinator Mr. Chandra Prakash for their encouragement and suggestions that we
were provided at different stages while working on this project and all the staff
members of our department for all the help that they have extended to us.
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.
TABLE OF CONTENTS
1. Abstract ………….………………………………………….
2. Introduction of Training……………………………………….
3. 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
• Request and Response
• Django Exceptions
Module 5: ………………………………………………….
• Django Session
• Django Cookie
Project
Module:………………………………………………
• Introduction
• Problem Statement
• Why we need ERP?
• Features, Methodology, Implementation, Identification and Viewpoint
• Flowchart
• Requirements
• Procedures, Codes and UI
4. Conclusion………………………………………………………..
5. Bibliography……………………………………………………..
1. ABSTRACT
This report discusses the training program during the period from Sept 2022 to Nov
2022. It states the concept of Python Django.
It shows a brief background about the place of training. It mentions some facts about the
department that was responsible for the training program. The report describes about the
history, characteristic, overview and concepts of Python Django.
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.
3. TRAINING CONTENT
Module 1
Prerequisites
Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript
Django Introduction
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.
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.
Django was released on 21, July 2005.
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.
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.
It prompts for login credentials if no password is created yet, use the following command to
create a user.
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.
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.
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.
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.
//views.py
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
First, we will import DateTime library that provides a method to get current date and time
and HttpResponse class. View calls when gets mapped with URL in urls.py.
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.
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.
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. ]
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.
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.
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.
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
This file contains a class that inherits ModelForm and mention the model name for which
HTML form is created.
// form.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
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
//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
// 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>
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)
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 = 10)
5. email = forms.EmailField(label="Enter Email")
6. file = forms.FileField() # for creating file input
//View (views.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, content types, and sessions.
The 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.
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.
1. python manage.py makemigrations
Migrations
// 0001_initial.py
1. from django.db import migrations, models
2. class Migration(migrations.Migration):
3. initial = True
4. dependencies = [
5. ]
6. operations = [
7. migrations.CreateModel(
8. name='Employee',
Submitted by Chirag Kathpalia
lOMoAR cPSD| 20149224
9. fields=[
10. ('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, ver bose_name='ID')),
11. ('eid', models.CharField(max_length=20)),
12. ('ename', models.CharField(max_length=100)),
13. ('econtact', models.CharField(max_length=15)),
14. ],
15. options={
16. 'db_table': 'employee',
17. },
18. ),
19. ]
After creating a migration, migrate it so that it reflects the database permanently. The
migrate command is given below.
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.XFrameOptionsMiddlewa
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.
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.
// views.py
1. def methodinfo(request):
2. return HttpResponse("Http request is: "+request.method)
// urls.py
1. path('info',views.methodinfo)
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.
MultipleObjectsReturned This exception is raised by a query if only one object is expected, but multiple 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.
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 the
following standard methods.
Let's see an example in which we will set and get session values. Two functions are
defined in the views.py file.
The first function is used to set and the second is used to get session values.
//views.py
// urls.py
Run Server
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.
In views.py, two functions setcookie() and getcookie() are used to set and get cookie respectively
// 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.
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/