0% found this document useful (0 votes)
8 views74 pages

Introduction to Django Framework

Django is a high-level Python web framework designed for rapid development of complex, database-driven websites. It features a Model-View-Template (MVT) architecture, built-in admin interface for CRUD operations, and emphasizes clean design and less code. The framework allows developers to create apps easily within a project, manage models and their fields, and run applications using simple command-line instructions.

Uploaded by

shruti kukkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views74 pages

Introduction to Django Framework

Django is a high-level Python web framework designed for rapid development of complex, database-driven websites. It features a Model-View-Template (MVT) architecture, built-in admin interface for CRUD operations, and emphasizes clean design and less code. The framework allows developers to create apps easily within a project, manage models and their fields, and run applications using simple command-line instructions.

Uploaded by

shruti kukkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Django?

Django is a web development framework for Python which offers standard


methods for fast and effective website development. The primary goal of this
high-level web framework is to create complex database-driven websites. It
helps you to build and maintain quality web applications. It enables you to
make the development process smooth and time-saving for rapid development.

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.

Install pip- Open command prompt and enter following command-


python -m pip install -U pip
django-introduction

Install virtual environment- Enter following command in cmd-


pip install virtualenv
django-introduce

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-

Create a virtual environment by giving this command in cmd-


virtualenv env_site
django-installation

Change directory to env_site by this command-


cd env_site
django-install

Go to Scripts directory inside env_site and activate virtual environment-


cd Scripts
activate
django-introduction-installation

Install Django- Install django by giving following command-


pip install django
django-basics

Return to the env_site directory-


cd ..
django

Start a project by following command-


django-admin startproject geeks_site
django-introduction-install

Change directory to geeks_site


cd geeks_site
django-introduction-project

Start the server- Start the server by typing following command in cmd-
python [Link] runserver

django-admin startproject projectname

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]: 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.

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.
init .py: It is an empty file that tells to the Python that this directory
should be considered as a Python package.

[Link]: This file is used to configure application settings such as


database connection, static files linking etc.

[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.

[Link]: 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.

To run the application, we can use the following command.

$ python3 [Link] runserver

Django Admin Interface

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).

The admin app ([Link]) 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:

Django Admin Interface


It prompts for login credentials if no password is created yet, use the
following command to create a user.

Create an Admin User


$ python3 [Link] createsuperuser
django admin interface 1
Now start development server and access admin login.

$ python3 [Link] runserver


Provide created username and password and login.

django admin interface 2


After login successfully, it shows the following interface.

django admin interface 3


It is a Django Admin Dashboard. Here, we can add and update the registered
models. The model registration process will be discussed in further chapters.

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.

$ python3 [Link] startapp appname


Django App Example
$ python3 [Link] startapp myapp
django app
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.

To run this application, we need to make some significant changes which


display hello world message on the browser.

Open [Link] file in any text editor and write the given code to it and do
the same for [Link] file too.

// [Link]

from [Link] import render

# Create your views here.


from [Link] import HttpResponse

def hello(request):
return HttpResponse("<h2>Hello, Welcome to Django!</h2>")
// [Link]

from [Link] import admin


from [Link] import path
from myapp import views

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.

Run the Application


$ python3 [Link] runserver

Let us start building an app.

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 :

python [Link] startapp projectApp


Method-2
To create a basic app in your Django project you need to go to the directory
containing [Link] and from there enter the command :

django-admin startapp projectApp


MVC Pattern
When talking about applications that provides UI (web or desktop), we usually talk
about MVC architecture. And as the name suggests, MVC pattern is based on three
components: Model, View, and Controller. Check our MVC tutorial here to know more.

DJANGO MVC - MVT Pattern


The Model-View-Template (MVT) is slightly different from MVC. In fact the main
difference between the two patterns is that Django itself takes care of the Controller
part (Software Code that controls the interactions between the Model and View),
leaving us with the template. The template is a HTML file mixed with Django Template
Language (DTL).

The following diagram illustrates how each of the components of the MVT pattern
interacts with each other to serve a user request -

DJANGO MVC - MVT Pattern


The developer provides the Model, the view and the template then just maps it to a URL
and Django does the magic to serve it to the user.

Django Admin Interface


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).

The admin app ([Link]) 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

1. $ python3 [Link] createsuperuser

Now start development server and access admin login.


1. $ python3 [Link] runserver

Provide created username and password and login.

After login successfully, it shows the following interface.


It is a Django Admin Dashboard. Here, we can add and update the registered models.
The model registration process will be discussed in further chapters.

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.

1. $ python3 [Link] startapp appname

Django App Example


1. $ python3 [Link] startapp myapp

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.

To run this application, we need to make some significant changes which


display hello world message on the browser.

Open [Link] file in any text editor and write the given code to it and do the same for
[Link] file too.

// [Link]

1. from [Link] import


render 2.
3. # Create your views here.
4. from [Link] import
HttpResponse 5.
6. def hello(request):
7. return HttpResponse("<h2>Hello, Welcome to Django!</h2>")
// [Link]

1. from [Link] import admin


2. from [Link] import path
3. from myapp import
views 4.
5. urlpatterns = [
6. path('admin/', [Link]),
7. path('hello/', [Link]),
8. ]

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.

Run the Application


1. $ python3 [Link] runserver

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 follow

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.

Django Model is a subclass of [Link] 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 [Link] 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. from [Link] import


models 2.
3. class Employee([Link]):
4. first_name = [Link](max_length=30)
5. last_name = [Link](max_length=30)

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.

1. CREATE TABLE appname_employee (


2. "id" INT NOT NULL PRIMARY KEY,
3. "first_name" varchar(30) NOT NULL,
4. "last_name" varchar(30) NOT NULL
5. );

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.

Register / Use Model


After creating a model, register model into the INSTALLED_APPS inside

[Link]. For example,

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.

Django provides various built-in fields types.

Field Name Class Particular

AutoField class AutoField(**options) It An IntegerField


that automatically
increments.

BigAutoField class BigAutoField(**options) It is a 64-bit integer, much


like an AutoField except that
it is guaranteed to fit
numbers from 1 to
9223372036854775807.

BigIntegerField class BigIntegerField(**options) It is a 64-bit integer, much


like an IntegerField except
that it is guaranteed to fit
numbers from -
9223372036854775808 to
9223372036854775807.

BinaryField class BinaryField(**options) A field to store raw binary


data.

BooleanField class BooleanField(**options) A true/false field. The default


form widget for this field is a
CheckboxInput.

CharField class It is a date, represented in


Python by a [Link]
DateField(auto_now=False, instance.
auto_now_add=False, **options)

DateTimeField class It is a date, represented in


DateTimeField(auto_now=False, Python by a [Link]
auto_now_add=False, **options) instance.
DateTimeField class It is used for date and time,
DateTimeField(auto_now=False, represented in Python by a
auto_now_add=False, **options) [Link] instance.

DecimalField class It is a fixed-precision decimal


DecimalField(max_digits=None, number, represented in
decimal_places=None, **options) Python by a Decimal
instance.

DurationField class DurationField(**options) A field for storing periods


of time.

EmailField class It is a CharField that checks


that the value is a valid
EmailField(max_length=254, email address.
**options)
FileField class It is a file-upload field.

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.

ImageField class It inherits all attributes and


methods from FileField, but
ImageField(upload_to=None, also validates that the
height_field=None, uploaded object is a valid
width_field=None, image.
max_length=100,
**options)
IntegerField class IntegerField(**options) It is an integer field. Values
from
-2147483648 to 2147483647
are
safe in all databases
supported by Django.
NullBooleanField class NullBooleanField(**options) Like a BooleanField, but
allows NULL as one of the
options.

PositiveIntegerFiel class Like an IntegerField, but


d PositiveIntegerField(**options) must be either positive or
zero (0). Values

from 0 to 2147483647 are


safe in all databases
supported by Django.

SmallIntegerField class SmallIntegerField(**options) It is like an IntegerField, but


only allows values under a
certain (database-
dependent) point.

TextField class TextField(**options) A large text field. The default


form widget for this field is a
Textarea.

TimeField class A time, represented in


Python by a [Link]
TimeField(auto_now=False, instance.
auto_now_add=False, **options)

Django Model Fields Example


1. first_name = [Link](max_length=50) # for creating varchar column
2. release_date = [Link]() # for creating date column
3. num_stars = [Link]() # for creating integer column

Field Options
Each field requires some arguments that are used to set column attributes. For
example, CharField requires mac_length to specify varchar database.

Common arguments available to all field types. All are optional.

Field Particulars
Options

Null Django will store empty values as NULL in the database.

Blank It is used to allowed field to be blank.

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.

primary_key This field is the primary key for the model.

Unique This field must be unique throughout the table.

Django Model Example

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]()

After that apply migration by using the following command.

1. python3 [Link] makemigrations myapp

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.

Django View Simple Example

//[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

HttpResponse 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 [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

class It is used to designate that a page hasn't been modified


HttpResponseNotModified since the user's last request (status code 304).

class It acts just like HttpResponse but uses a 400 status


HttpResponseBadRequest code.

class It acts just like HttpResponse but uses a 404 status


HttpResponseNotFound code.

class It acts just like HttpResponse but uses a 410 status


HttpResponseNotAllowed code.

HttpResponseServerError It acts just like HttpResponse but uses a 500 status


code.

Django View Example

// [Link]

1. from [Link] import render


2. # Create your views here.
3. from [Link] import HttpResponse, HttpResponseNotFound
4. def index(request):
5. a=1
6. if a:
7. return HttpResponseNotFound('<h1>Page not found</h1>')
8. else:
9. return HttpResponse('<h1>Page was found</h1>') # rendering the template in HttpResponse

Output:
Django View HTTP Decorators
HTTP Decorators are used to restrict access to view based on the request method.

These decorators are listed in [Link] and return


a [Link] if the conditions are not met.

Syntax

require_http_methods(request_method_list)

Django Http Decorator Example

//[Link]

1. from [Link] import render


2. # Create your views here.
3. from [Link] import HttpResponse, HttpResponseNotFound
4. from [Link] import require_http_methods
5. @require_http_methods(["GET"])
6. def show(request):
7. return HttpResponse('<h1>This is Http GET request.</h1>')

This method will execute only if the request is an HTTP GET request.
//[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. path('show/', [Link]),
8. ]

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.

Why Django Template?


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

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

Django Template Configuration


To configure the template system, we have to provide some entries in [Link] file.

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. ]

Here, we mentioned that our template directory name is templates. By default,


DjangoTemplates looks for a templates subdirectory in each of the INSTALLED_APPS.

Django Template Simple Example

First, create a directory templates inside the project app as we did below.
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]

1. from [Link] import render


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

HttpResponse Set a URL to access the template from the browser.

//[Link]

1. path('index/', [Link]),

Register app inside the INSTALLED_APPS

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.

1. $ python3 [Link] runserver

Django Template Language


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

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

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

Django Variable Example

//[Link]

1. from [Link] import render


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

//[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.

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

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

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, [Link] module is used by the framework.

Let's open the file [Link] of the project and see the what it looks like:

// [Link]

1. from [Link] import admin


2. from [Link] import
path 3.
4. urlpatterns = [
5. path('admin/', [Link]),
6. ]

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.

The [Link] module contains various functions, path(route,view,kwargs,name)


is one of those which is used to map the URL and call the specified view.

Django URL Functions


Here, we are giving some commonly used functions for URL handling and mapping.

Name Description Example

path(route, view, It returns an element path('index/',


kwargs=None, name=None) for inclusion in [Link],
urlpatterns. name='main-
view')
re_path(route, It returns an element re_path(r'^index/$',
for inclusion in [Link],
view, kwargs=None, urlpatterns. name='index'),
name=None)
include(module, It is a function that takes a
namespace=None) full Python import path to
another
URLconf module that should
be "included" in this place.
register_converter(converter It is used for registering a
, type_name) converter for use in path()
routes.

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]

1. from [Link] import render


2. # Create your views here.
3. from [Link] import HttpResponse, HttpResponseNotFound
4. from [Link] import require_http_methods
5. @require_http_methods(["GET"])
6. def hello(request):
7. return HttpResponse('<h1>This is Http GET request.</h1>')

// [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. path('hello/', [Link]),
8. ]
Now, start the server and enter localhost:8000/hello to the browser. This URL will be
mapped into the list of URLs and then call the corresponding function from the views
file.

In this example, hello will be mapped and call hello function from the views file. It is
called URL mapping.

Django Static Files Handling


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

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

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

The [Link] module helps to manage them.

Play Videox

Django Static (CSS, JavaScript, images) Configuration


1. Include the [Link] in INSTALLED_APPS.

1. INSTALLED_APPS = [
2. '[Link]',
3. '[Link]',
4. '[Link]',
5. '[Link]',
6. '[Link]',
7. '[Link]',
8. 'myapp'
9. ]

2. Define STATIC_URL in [Link] file as given below.

1. STATIC_URL = '/static/'

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

1. {% load static %}

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

Our project structure looks like this.


Django Image Loading Example
To load an image in a template file, use the code given below.

// [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]')

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.

Django Loading JavaScript


To load JavaScript file, just add the following line of code in [Link] file.

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]

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

Now, our project structure looks like this:


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.
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. }

Our project structure looks like this:


// [Link]

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>

Run the server by using python [Link] runserver command.

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 Model Form


It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code.

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. Let's see an example.

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.

// [Link]

1. from future import unicode_literals


2. from [Link] import
models 3.
4. class Student([Link]):
5. first_name = [Link](max_length=20)
6. last_name = [Link](max_length=30)
7. class Meta:
8. db_table = "student"

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 "

Write a view function to load the ModelForm from [Link].

//[Link]

1. from [Link] import render


2. from [Link] import
StuForm 3.
4. def index(request):
5. stu = EmpForm()
6. return render(request,"[Link]",{'form':stu})

//[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. ]

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

does not require the Model.

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

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

1. from django import forms


2. class StudentForm([Link]):
3. firstname = [Link](label="Enter first name",max_length=50)
4. lastname = [Link](label="Enter last name", max_length = 100)

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

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

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

1. <label for="id_firstname">Enter first name:</label>


2. <input type="text" name="firstname" required maxlength="50" id="id_firstname" />
3. <label for="id_lastname">Enter last name:</label> <input type="text" name="lastname" required maxlength="100" id="id_lastname" />
Note: Django Form does not include <form> tags, or a submit button. We'll have to provide those ourselves in the template.

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

Name Class HTML Input Empty value

BooleanField class CheckboxInput False


BooleanField(**kwargs)

CharField class CharField(**kwargs) TextInput Whatever you've given as


empty_value.

ChoiceField class ChoiceField(**kwargs)Select (an empty string)

DateField class DateField(**kwargs) DateInput None

DateTimeField class DateTimeInput None


DateTimeField(**kwarg
s)

DecimalField class NumberInput None


DecimalField(**kwar
gs)

EmailField class EmailField(**kwargs) EmailInput (an empty string)

FileField class FileField(**kwargs) ClearableFileInput None

ImageField class ImageField(**kwargs)ClearableFileInput None

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

Building a Form in Django


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

1. from django import forms


2. class StudentForm([Link]):
3. firstname = [Link](label="Enter first name",max_length=50)
4. lastname = [Link](label="Enter last name",

max_length = 100) Put this code into the [Link] file.

Instantiating Form in Django


Now, we need to instantiate the form in [Link] file. See, the below code.

// [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>

Provide the URL in [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. ]

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:

o {{ form.as_table }} will render them as table cells wrapped in <tr> tags


o {{ form.as_p }} will render them wrapped in <p> tags
o {{ form.as_ul }} will render them wrapped in <li> tags

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

Django Form Validation


Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF
tokens. It uses uses a clean and easy approach to validate data.

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.

Django Validation Example

This example contains the following files and code.

// [Link]

1. from [Link] import models


2. class Employee([Link]):
3. eid = [Link](max_length=20)
4. ename = [Link](max_length=100)
5. econtact = [Link](max_length=15)
6. class Meta:
7. db_table = "employee"
Now, create a form which contains the below code.

// [Link]

1. from django import forms


2. from [Link] import
Employee 3.
4. class EmployeeForm([Link]):
5. class Meta:
6. model = Employee
7. fields = " all "

Instantiate the form


Instantiate the form, check whether request is post or not. It validate the data by using is_valid() method.

//[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]',

{'form':form}) Index template that shows

form and errors.

// [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>

Start server and access the form.


It validates each field and throws errors if any validation fails.

Django File Upload


File upload to the server using Django is a very easy task. Django provides built-in library and methods that help to upload a file to the server.

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])

It will create an HTML form which contains a file input component.

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])

1. from django import forms


2. class StudentForm([Link]):
3. firstname = [Link](label="Enter first name",max_length=50)
4. lastname = [Link](label="Enter last name", max_length = 10)
5. email = [Link](label="Enter Email")
6. file = [Link]() # for creating file input

View ([Link])

Here, one extra parameter [Link] is required in the constructor. This argument contains the uploaded file instance.

1. from [Link] import render


2. from [Link] import HttpResponse
3. from [Link] import handle_uploaded_file
4. from [Link] import StudentForm
5. def index(request):
6. if [Link] == 'POST':
7. student = StudentForm([Link], [Link])
8. if student.is_valid():
9. handle_uploaded_file([Link]['file'])
10. return HttpResponse("File uploaded successfuly")
11. else:
12. student = StudentForm()
13. return render(request,"[Link]",{'form':student})

Specify URL ([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. ]

Upload Script ([Link])

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

1. python [Link] runserver

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.

1. $ python3 [Link] migrate

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]

1. from [Link] import models


2. class Employee([Link]):
3. eid = [Link](max_length=20)
4. ename = [Link](max_length=100)
5. econtact = [Link](max_length=15)
6. class Meta:
7. db_table = "employee"

Django first creates a migration file that contains the details of table structure. To create migration use the following command.

1. $ python3 [Link] makemigrations

The created migration file is located into migrations folder and contains the following code.

1. from [Link] import migrations, models


2. class Migration([Link]):
3. initial = True
4. dependencies = [
5. ]
6. operations = [
7. [Link](
8. name='Employee',
9. fields=[
10. ('id', [Link](auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
11. ('eid', [Link](max_length=20)),
12. ('ename', [Link](max_length=100)),
13. ('econtact', [Link](max_length=15)),
14. ],
15. options={
16. 'db_table': 'employee',
17. },
18. ),
19. ]

Now, migrate to reflect the changes into the database.

1. $ python3 [Link] migrate


Check the database again, now it contains the employee table.

See, a table is present in the database. Well, we have successfully established a connection between our Django
application and MySQL database.

Django Database Migrations


Migration is a way of applying changes that we have made to a model, into the database schema. Django creates a
migration file inside the migration folder for each model to create the table schema, and each table is mapped to the
model of which migration is created.

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]

1. from [Link] import models


2. class Employee([Link]):
3. eid = [Link](max_length=20)
4. ename = [Link](max_length=100)
5. econtact = [Link](max_length=15)
6. class Meta:
7. db_table = "employee"

To create a migration for this model, use the following command. It will create a migration file inside the migration folder.

1. $ python3 [Link] makemigrations

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

1. from [Link] import migrations, models


2. class Migration([Link]):
3. initial = True
4. dependencies = [
5. ]
6. operations = [
7. [Link](
8. name='Employee',
9. fields=[
10. ('id', [Link](auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
11. ('eid', [Link](max_length=20)),
12. ('ename', [Link](max_length=100)),
13. ('econtact', [Link](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.

1. $ python3 [Link] migrate

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.

1. $ python3 [Link] migrate

And showmigrations command is used to show applied migrations. See the

example. If no app-name is provided, it shows all migrations applied to

the project.

1. $ python3 [Link] showmigrations


We can get app-specific migrations by specifying app-name, see the example.

1. $ python3 [Link] showmigrations myapp


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.

Put [Link] in MIDDLEWARE and [Link] in


INSTALLED_APPS of [Link] file.

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

getitem (key) It is used to get session value.

setitem (key, It is used to set session value.


value)

delitem (key) It is used to delete session object.

contains (key) It checks whether the container contains the particular session
object or not.

get(key, It is used to get session value of the specified key.


default=None)

Let's see an example in which we will set and get session values. Two functions are defined in the [Link] file.

Django Session Example

The first function is used to set and the second is used to get session values.

//[Link]

1. from [Link] import render


2. from [Link] import
HttpResponse 3.
4. def setsession(request):
5. [Link]['sname'] = 'irfan'
6. [Link]['semail'] = '[Link]@[Link]'
7. return HttpResponse("session is set")
8. def getsession(request):
9. studentname = [Link]['sname']
10. studentemail = [Link]['semail']
11. return HttpResponse(studentname+"

"+studentemail); Url mapping to call both the

functions.
// [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. path('ssession',[Link]),
8. path('gsession',[Link])
9. ]

Run Server

1. $ python3 [Link] runserver

And set the session by using localhost:8000/ssession

The session has been set, to check it, use localhost:8000/gsession


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.

Put [Link] in MIDDLEWARE and [Link] in


INSTALLED_APPS of [Link] file.

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

getitem (key) It is used to get session value.

setitem (key, It is used to set session value.


value)

delitem (key) It is used to delete session object.

contains (key) It checks whether the container contains the particular session
object or not.

get(key, It is used to get session value of the specified key.


default=None)

Let's see an example in which we will set and get session values. Two functions are defined in the [Link] file.

Django Session Example

The first function is used to set and the second is used to get session values.

//[Link]

1. from [Link] import render


2. from [Link] import
HttpResponse 3.
4. def setsession(request):
5. [Link]['sname'] = 'irfan'
6. [Link]['semail'] = '[Link]@[Link]'
7. return HttpResponse("session is set")
8. def getsession(request):
9. studentname = [Link]['sname']
10. studentemail = [Link]['semail']
11. return HttpResponse(studentname+"

"+studentemail); Url mapping to call both the

functions.
// [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. path('ssession',[Link]),
8. path('gsession',[Link])
9. ]

Run Server

1. $ python3 [Link] runserver

And set the session by using localhost:8000/ssession

The session has been set, to check it, use localhost:8000/gsession


Create CSV with Django
Django uses Python's built-in CSV library to create Dynamic CSV (Comma Separated Values) file. We can use this library in
our project's view file.

Let's see an example, here we have a Django project to which we are implementing this feature. A view function getfile() is created.

Django CSV Example

In this example, we are creating CSV using static data.

//

[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]

Provide url for the function.

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.

Dynamic CSV using Database


// [Link]

1. from [Link] import Employee import csv


2. def getfile(request):
3. response = HttpResponse(content_type='text/csv')
4. response['Content-Disposition'] = 'attachment; filename="[Link]"'
5. employees = [Link]()
6. writer = [Link](response)
7. for employee in employees:
8. [Link]([[Link],[Link],[Link]])
9. return response

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.

1. $ pip install reportlab


After installing, we can import it by import keyword in the view file.

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]

1. from [Link] import canvas


2. from [Link] import
HttpResponse 3.
4. def getpdf(request):
5. response = HttpResponse(content_type='application/pdf')
6. response['Content-Disposition'] = 'attachment; filename="[Link]"'
7. p = [Link](response)
8. [Link]("Times-Roman", 55)
9. [Link](100,700, "Hello, Javatpoint.")
10. [Link]()
11. [Link]()
12. return response

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])

Set the above code in [Link] to call view function.

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.

In Django, we can use bootstrap to create more user friendly

applications. To implement bootstrap, we need to follow the

following steps.

[Link] the Bootstrap

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.

[Link] the Boostrap

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

bootstrap. Finally, out project structure looks like this.

You might also like