Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

PFSD

CO3

Introduction to Web
Web consists of billions of clients and server connected through wires and wireless networks.
The web clients make requests to web server. The web server receives the request, finds the
resources and return the response to the client. When a server answers a request, it usually sends
some type of content to the client. The client uses web browser to send request to the server. The
server often sends response to the browser with a set of instructions written in HTML(HyperText
Markup Language). All browsers know how to display HTML page to the client.

Django
Django is a Python-based web framework that allows you to quickly create efficient web
applications. It is also called batteries included framework because Django provides built-in
features for everything including Django Admin Interface, default database – SQLlite3, etc. When
you’re building a website, you always need a similar set of components: a way to handle user
authentication (signing up, signing in, signing out), a management panel for your website, forms, a
way to upload files, etc. Django gives you ready-made components to use and that too for rapid
development.
Why Django Framework ?

 Excellent documentation and high scalability.


 Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube,
Bitbucket, Dropbox, etc. and the list is never-ending.
 Easiest Framework to learn, rapid development and Batteries fully included.
 The last but not least reason to learn Django is Python, Python has huge library and features
such as Web Scrapping, Machine Learning, Image Processing, Scientific Computing, etc.
One can integrate it all this with web application and do lots and lots of advance stuff.

Django Introduction and Installation


Django is a Python-based web framework which allows you to quickly create web application
without all of the installation or dependency problems that you normally will find with other
frameworks.
When you’re building a website, you always need a similar set of components: a way to handle
user authentication (signing up, signing in, signing out), a management panel for your website,
forms, a way to upload files, etc. Django gives you ready-made components to use.

Why Django?

1. It’s very easy to switch database in Django framework.


2. It has built-in admin interface which makes easy to work with it.
3. Django is fully functional framework that requires nothing else.
4. It has thousands of additional packages available.
5. It is very scalable.

Popularity of Django

Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur
Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on the
Django framework. ( Source ) Sites like Hot Frameworks assess the popularity of a framework by
counting the number of GitHub projects and StackOverflow questions for each platform, here
Django is in 6th position. Web frameworks often refer to themselves as “opinionated” or “un-
opinionated” based on opinions about the right way to handle any particular task. Django is
somewhat opinionated, hence delivers the in both worlds ( opinionated & un-opinionated ).

Features of Django

Versatility of Django

Django can build almost any type of website. It can also work with any client-side framework and
can deliver content in any format such as HTML, JSON, XML etc. Some sites which can be built
using Django are wikis, social networks, new sites etc.

Security
Since Django framework is made for making web development easy, it has been engineered in
such a way that it automatically do the right things to protect the website. For example, In the
Django framework instead of putting a password in cookies, the hashed password is stored in it so
that it can’t be fetched easily by hackers.

Scalability
Django web nodes have no stored state, they scale horizontally – just fire up more of then when
you need them. Being able to do this is the essence of good scalability. Instagram and Disqus are
two Django based products that have millions of active users, this is taken as an example of the
scalability of Django.

Portability
All the codes of the Django framework are written in Python, which runs on many platforms.
Which leads to run Django too in many platforms such as Linux, Windows and Mac OS.

Installation of Django

 Install python3 if not installed in your system ( according to configuration of your


system and OS) from here . Try to download the latest version of python it’s python3.6.4
this time.
Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows
for Linux and mac just open terminal in place of command prompt and go through the
following commands.
 Install pip- Open command prompt and enter following command-
python -m pip install -U pip
 Install virtual environment- Enter following command in cmd-
pip install virtualenv
 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-

1. Create a virtual environment by giving this command in cmd-


virtualenv env_site
2. Change directory to env_site by this command-
cd env_site
3. Go to Script directory inside env_site and activate virtual environment-
cd Script
activate
 Install Django- Install django by giving following command-
pip install django
 Return to the env_site directory-
cd ..
 Start a project by following command-
django-admin startproject geeks_site
 Change directory to geeks_site
cd geeks_site
 Start the server- Start the server by typing following command in cmd-
python manage.py runserver

To check whether server is running or not go to web browser and enter http://127.0.0.1:8000/ as
url.

Django Basics

Django is a Python-based web framework which allows you to quickly create web application
without all of the installation or dependency problems that you normally will find with other
frameworks.
When you’re building a website, you always need a similar set of components: a way to handle
user authentication (signing up, signing in, signing out), a management panel for your website,
forms, a way to upload files, etc. Django gives you ready-made components to use.
 Django is a rapid web development framework that can be used to develop fully fleshed web
applications in a short period of time.
 It’s very easy to switch database in Django framework.
 It has built-in admin interface which makes easy to work with it.
 Django is fully functional framework that requires nothing else.
 It has thousands of additional packages available.
 It is very scalable. For more visit When to Use Django? Comparison with other
Development Stacks ?

Django architecture

Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern


for developing a web application.
MVT Structure has the following three parts –
Model: Model is going to act as the interface of your data. It is responsible for maintaining data. It
is the logical data structure behind the entire application and is represented by a database (generally
relational databases such as MySql, Postgres).
View: The View is the user interface — what you see in your browser when you render a website.
It is represented by HTML/CSS/Javascript and Jinja files.
Template: A template consists of static parts of the desired HTML output as well as some special
syntax describing how dynamic content will be inserted.
To check more about Django’s architecture, visit Django Project MVT Structure

Installation of Django

 Install python3 if not installed in your system ( according to configuration of your system
and OS) from here . Try to download the latest version of python it’s python3.6.4 this time.
Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for
Linux and mac just open terminal in place of command prompt and go through the following
commands.
 Install pip- Open command prompt and enter following command-
python -m pip install -U pip
 Install virtual environment- Enter following command in cmd-
pip install virtualenv
 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-
1. Create a virtual environment by giving this command in cmd-
virtualenv env_site
2. Change directory to env_site by this command-
cd env_site
3. Go to Script directory inside env_site and activate virtual environment-
cd Script
activate
 Install Django- Install django by giving following command-
pip install django

Creating a Project

Lets’ check how to create a basic project using Django after you have installed it in your pc.
 To initiate a project of Django on Your PC, open Terminal and Enter the following
command
django-admin startproject projectName
 A New Folder with name projectName will be created. To enter in the project using
terminal enter command
cd projectName
 Now run,
Python manage.py runserver
Now visit http://localhost:8000/,

Creating an App

Django is famous for its unique and fully managed app structure. For every functionality, an app
can be created like a completely independent module. This article will take you through how to
create a basic app and add functionalities using that app.
 To create a basic app in your Django project you need to go to directory
containing manage.py and from there enter the command :
python manage.py startapp projectApp
Now you can see your directory structure as under:

 To consider the app in your project you need to specify your project name in
INSTALLED_APPS list as follows in settings.py:
# Application definition

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'projectApp'

 So, we have finally created an app but to render the app using urls we need to include the
app in our main project so that urls redirected to that app can be rendered. Let us explore it.
Move to projectName-> projectName -> urls.py and add below code in the header

from django.urls import include


Now in the list of URL patterns, you need to specify app name for including your app urls.
Here is the code for it –

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

# Enter the app name in following syntax for this to work

path('', include("projectApp.urls")),

]
Project Structure :

A Django Project when initialised contains basic files by default such as manage.py, view.py, etc.
A simple project structure is enough to create a single page application. Here are the major files
and there explanations. Inside the geeks_site folder ( project folder ) there will be following files-

manage.py-This file is used to interact with your project via the command line(start the server,
sync the database… etc). For getting the full list of command that can be executed by manage.py
type this code in the command window-

$ python manage.py help

folder ( geeks_site ) – This folder contains all the packages of your project. Initially it contains
four files –
 _init_.py – It is python package.
 settings.py – As the name indicates it contains all the website settings. In this file we
register any applications we create, the location of our static files, database configuration
details, etc.
 urls.py – In this file we store all links of the project and functions to call.
 wsgi.py – This file is used in deploying the project in WSGI. It is used to help your Django
application communicate with the web server.

Views In Django
Django Views are one of the vital participants of MVT Structure of Django. A View is the user
interface — what you see in your browser when you render a website. It is represented by
HTML/CSS/Javascript and Jinja files. As per Django Documentation, A view function is a Python
function that takes a Web request and returns a Web response. This response can be the HTML
contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything
that a web browser can display.

Django View Example

Illustration of How to create and use a Django view using an Example. Consider a project
named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.
 How to Create a Basic Project using MVT in Django?
 How to Create an App in Django ?

After you have a project ready, we can create a view in geeks/views.py,

# import Http Response from django

from django.http import HttpResponse

# get datetime

import datetime

# create a function

def geeks_view(request):

# fetch date and time

now = datetime.datetime.now()

# convert to string

html = "Time is {}".format(now)

# return response

return HttpResponse(html)

Let’s step through this code one line at a time:


 First, we import the class HttpResponse from the django.http module, along with Python’s
datetime library.
 Next, we define a function called geeks_view. This is the view function. Each view function
takes an HttpRequest object as its first parameter, which is typically named request.
 The view returns an HttpResponse object that contains the generated response. Each view
function is responsible for returning an HttpResponse object.
For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle –
HttpRequest and HttpResponse Objects. Let’s get this view to working, in geeks/urls.py,
from django.urls import path

# importing views from views..py

from .views import geeks_view

urlpatterns = [

path('', geeks_view),

Now, visit http://127.0.0.1:8000/,

To check how to make a basic project using MVT (Model, View, Template) structure of Django,
visit Creating a Project Django.

Types of Views

Django views are divided into two major categories :-


 Function Based Views
 Class Based Views
Function Based Views

Function based views are writter using a function in python which recieves as an argument
HttpRequest object and returns an HttpResponse Object. Function based views are generally
divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of
any framework one is using for development.

Function based view Example –

Let’s Create a function based view list view to display instances of a model.
let’s create a model of which we will be creating instances through our view. In geeks/models.py,

# import the standard Django Model

# from built-in library

from django.db import models

# declare a new model with a name "GeeksModel"

class GeeksModel(models.Model):
# fields of the model

title = models.CharField(max_length = 200)

description = models.TextField()

# renames the instances of the model

# with their title name

def __str__(self):

return self.title

After creating this model, we need to run two commands in order to create Database for the same.

Python manage.py makemigrations


Python manage.py migrate
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
title="title1",
description="description1").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
Now if you want to see your model and its data in the admin panel, then you need to register your
model.
Let’s register this model. In geeks/admin.py,
from django.contrib import admin

from .models import GeeksModel

# Register your models here.

admin.site.register(GeeksModel)

Now we have everything ready for back end. Verify that instnaces have been created
from http://localhost:8000/admin/geeks/geeksmodel/

Let’s create a view and template for the same. In geeks/views.py,

from django.shortcuts import render

# relative import of forms

from .models import GeeksModel


def list_view(request):

# dictionary for initial data with

# field names as keys

context ={}

# add the dictionary during initialization

context["dataset"] = GeeksModel.objects.all()

return render(request, "list_view.html", context)

Create a template in templates/list_view.html,

<div class="main">

{% for data in dataset %}.

{{ data.title }}<br/>

{{ data.description }}<br/>

<hr/>

{% endfor %}

</div>

Let’s check what is there on http://localhost:8000/


Class Based Views

Class-based views provide an alternative way to implement views as Python objects instead of
functions. They do not replace function-based views, but have certain differences and advantages
when compared to function-based views:
 Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed
by separate methods instead of conditional branching.
 Object oriented techniques such as mixins (multiple inheritance) can be used to factor code
into reusable components.
Class-based views are simpler and efficient to manage than function-based views. A function-
based view with tons of lines of code can be converted into a class-based views with few lines
only. This is where Object-Oriented Programming comes into impact.

Class based view Example –

from django.views.generic.list import ListView

from .models import GeeksModel


class GeeksList(ListView):

# specify the model for list view

model = GeeksModel

Now create a URL path to map the view. In geeks/urls.py,

from django.urls import path

# importing views from views..py

from .views import GeeksList

urlpatterns = [

path('', GeeksList.as_view()),

Create a template in templates/geeks/geeksmodel_list.html,

<ul>

<!-- Iterate over object_list -->

{% for object in object_list %}

<!-- Display Objects -->

<li>{{ object.title }}</li>

<li>{{ object.description }}</li>

<hr/>

<!-- If objet_list is empty -->

{% empty %}

<li>No objects yet.</li>

{% endfor %}
</ul>

Let’s check what is there on http://localhost:8000/

Django URL Mapping

Well, till here, we have learned to create a model, view, and template. Now, we will learn about
the routing of application.

Since Django is a web application framework, it gets user requests by URL locater and responds
back. To handle URL, django.urls module is used by the framework.
Name Description Example

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


kwargs=None, inclusion in urlpatterns. name='main-view')
name=None)

re_path(route, view, It returns an element for re_path(r'^index/$',


kwargs=None, inclusion in urlpatterns. views.index, 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(conve It is used for registering a


rter, type_name) converter for use in path()
routes.

Let's open the file urls.py of the project and see the what it looks like:

// urls.py

from django.contrib import admin


from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls), ]

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 django.urls 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.

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 views.py file. This function will be mapped from the url.py file.

// views.py

from django.shortcuts import render


# Create your views here.
from django.http import HttpResponse, HttpResponseNotFound
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def hello(request):
return HttpResponse('<h1>This is Http GET request.</h1>')

// urls.py

from django.contrib import admin


from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('hello/', views.hello),
]

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.

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

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 settings.py file.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

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 index.html inside the created folder.

Our template index.html contains the following code.

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Welcome to Django!!!</h2>
</body>
</html>

Loading Template

To load the template, call get_template() method as we did below and pass template name.

//views.py

from django.shortcuts import render


#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
template = loader.get_template('index.html') # getting our template
return HttpResponse(template.render()) # rendering the template in HttpResponse

Set a URL to access the template from the browser.

//urls.py

1. path('index/', views.index),

Register app inside the INSTALLED_APPS

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]

Run Server

Execute the following command and access the template by entering localhost:8000/index at the
browser.

$ python3 manage.py 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.

My name is {{name}}.
My name is rahul

Django Variable Example

//views.py

from django.shortcuts import render


#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
template = loader.get_template('index.html') # getting our template
name = {
'student':'rahul'
}
return HttpResponse(template.render(name)) # rendering the template in HttpResponse

//index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Welcome to Django!!!</h2>
<h3>My Name is: {{ student }}</h3>
</body>
</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.

{% csrf_token %}

{% if user.is_authenticated %}
Hello, {{ user.username }}.
{% endif %}

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.

from django.db import models

class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

The first_name and last_name fields are specified as class attributes and each attribute maps to
a database column.

This model will create a table into the database that looks like below.

CREATE TABLE appname_employee (


"id" INT NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);

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 settings.py.
For example,

INSTALLED_APPS = [
#...
'appname',
#...
]

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 It is a 64-bit integer, much like an IntegerField


BigIntegerField(**options) 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


DateField(auto_now=False, datetime.date instance.
auto_now_add=False,
**options)

DateTimeField class It is a date, represented in Python by a


DateTimeField(auto_now=Fal datetime.date instance.
se, auto_now_add=False,
**options)

DateTimeField class It is used for date and time, represented in


DateTimeField(auto_now=Fal Python by a datetime.datetime instance.
se, auto_now_add=False,
**options)

DecimalField class It is a fixed-precision decimal number,


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

DurationField class A field for storing periods of time.


DurationField(**options)

EmailField class It is a CharField that checks that the value is a


EmailField(max_length=254, valid 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


ImageField(upload_to=None, FileField, but also validates that the uploaded
height_field=None, object is a valid image.
width_field=None,
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.

NullBooleanFie class Like a BooleanField, but allows NULL as one


ld NullBooleanField(**options) of the options.

PositiveInteger class Like an IntegerField, but must be either


PositiveIntegerField(**option positive or zero (0). Values from 0 to
Field s) 2147483647 are safe in all databases
supported by Django.

SmallIntegerFie class It is like an IntegerField, but only allows


ld SmallIntegerField(**options) 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


TimeField(auto_now=False, datetime.time instance.
auto_now_add=False,
**options)

Django Model Fields Example


first_name = models.CharField(max_length=50) # for creating varchar column
release_date = models.DateField() # for creating date column
num_stars = models.IntegerField() # 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 models.py file.

//models.py

class Student(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
contact = models.IntegerField()
email = models.EmailField(max_length=50)
age = models.IntegerField()

After that apply migration by using the following command.

python manage.py makemigrations myapp

Django Redirects: Example


In Django, you redirect the user to another URL by returning an instance
of HttpResponseRedirect or HttpResponsePermanentRedirect from your view. The simplest way
to do this is to use the function redirect() from the module django.shortcuts. Here’s an example:

# views.py
from django.shortcuts import redirect

def redirect_view(request):
response = redirect('/redirect-success/')
return response

Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which
you then return from your view.

A view returning a redirect has to be added to your urls.py, like any other view:
# urls.py
from django.urls import path

from .views import redirect_view

urlpatterns = [
path('/redirect/', redirect_view)
# ... more URL patterns here
]

Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects
to /redirect-success/.

To avoid hard-coding the URL, you can call redirect() with the name of a view or URL pattern
or a model to avoid hard-coding the redirect URL. You can also create a permanent redirect by
passing the keyword argument permanent=True.

This article could end here, but then it could hardly be called “The Ultimate Guide to Django
Redirects.” We will take a closer look at the redirect() function in a minute and also get into the
nitty-gritty details of HTTP status codes and different HttpRedirectResponse classes, but let’s
take a step back and start with a fundamental question.

Why Redirect
You might wonder why you’d ever want to redirect a user to a different URL in the first place.
To get an idea where redirects make sense, have a look at how Django itself incorporates
redirects into features that the framework provides by default:

 When you are not logged-in and request a URL that requires authentication, like the
Django admin, Django redirects you to the login page.
 When you log in successfully, Django redirects you to the URL you requested originally.
 When you change your password using the Django admin, you are redirected to a page
that indicates that the change was successful.
 When you create an object in the Django admin, Django redirects you to the object list.

What would an alternative implementation without redirects look like? If a user has to log in to
view a page, you could simply display a page that says something like “Click here to log in.”
This would work, but it would be inconvenient for the user.

URL shorteners like http://bit.ly are another example of where redirects come in handy: you type
a short URL into the address bar of your browser and are then redirected to a page with a long,
unwieldy URL.
In other cases, redirects are not just a matter of convenience. Redirects are an essential
instrument to guide the user through a web application. After performing some kind of operation
with side effects, like creating or deleting an object, it’s a best practice to redirect to another
URL to prevent accidentally performing the operation twice.

One example of this use of redirects is form handling, where a user is redirected to another URL
after successfully submitting a form. Here’s a code sample that illustrates how you’d typically
handle a form:

from django import forms


from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render

def send_message(name, message):


# Code for actually sending the message goes here

class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea)

def contact_view(request):
# The request method 'POST' indicates
# that the form was submitted
if request.method == 'POST': # 1
# Create a form instance with the submitted data
form = ContactForm(request.POST) # 2
# Validate the form
if form.is_valid(): # 3
# If the form is valid, perform some kind of
# operation, for example sending a message
send_message(
form.cleaned_data['name'],
form.cleaned_data['message']
)
# After the operation was successful,
# redirect to some other page
return redirect('/success/') # 4
else: # 5
# Create an empty form instance
form = ContactForm()

return render(request, 'contact_form.html', {'form': form})

The purpose of this view is to display and handle a contact form that allows the user to send a
message. Let’s follow it step by step:

1. First the view looks at the request method. When the user visits the URL connected to
this view, the browser performs a GET request.
2. If the view is called with a POST request, the POST data is used to instantiate
a ContactForm object.
3. If the form is valid, the form data is passed to send_message(). This function is not
relevant in this context and therefore not shown here.
4. After sending the message, the view returns a redirect to the URL /success/. This is the
step we are interested in. For simplicity, the URL is hard-coded here. You’ll see later
how you can avoid that.
5. If the view receives a GET request (or, to be precise, any kind of request that is not
a POST request), it creates an instance of ContactForm and
uses django.shortcuts.render() to render the contact_form.html template.

If the user now hits reload, only the /success/ URL is reloaded. Without the redirect, reloading
the page would re-submit the form and send another message.

The redirect() Function


To make your life easier, Django provides the versatile shortcut function you’ve already seen in
the introduction: django.shortcuts.redirect().

You can call this function with:

 A model instance, or any other object, with a get_absolute_url() method


 A URL or view name and positional and/or keyword arguments
 A URL

It will take the appropriate steps to turn the arguments into a URL and return
an HTTPResponseRedirect. If you pass permanent=True, it will return an instance
of HttpResponsePermanentRedirect, resulting in a permanent redirect.

Here are three examples to illustrate the different use cases:

Passing a model:

from django.shortcuts import redirect


def model_redirect_view(request):
product = Product.objects.filter(featured=True).first()
return redirect(product)

redirect() will call product.get_absolute_url() and use the result as redirect target. If the
given class, in this case Product, doesn’t have a get_absolute_url() method, this will fail with
a TypeError.

Passing a URL name and arguments:

from django.shortcuts import redirect

def fixed_featured_product_view(request):
...
product_id = settings.FEATURED_PRODUCT_ID
return redirect('product_detail', product_id=product_id)

redirect() will try to use its given arguments to reverse a URL. This example assumes your
URL patterns contain a pattern like this:

path('/product/<product_id>/', 'product_detail_view', name='product_detail')\

Passing a URL:

from django.shortcuts import redirect

def featured_product_view(request):
return redirect('/products/42/')
redirect() will treat any string containing a / or . as a URL and use it as redirect target.

Setup Sending Email in Django Project

Haven’t you observed, when you register on some websites, you get a mail from that company or
institution? The email would be, verification email or welcome email, account creation successful
email or thanks-regard email, etc. For example, when you create a Google account, the first mail
you get would be something like, “Hi Xyz, Welcome to Google. Your new account comes with
access to Google products, apps, and services…..” Sending these types of emails from your Django
application is quite easy.
Although you can refer to the documentation for knowing more about sending emails in Django,
but this is remarkably condensed and made easier.
How to send simple emails to the registered users of your Django application
Illustration of Django emails using an example. Consider a project named geeksforgeeks having an
app named geeks. Refer this to create Django project and apps. Now let’s demonstrate this in
geeksforgeeks project. In your “geeks” app’s settings.py file, enter the following,

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = #sender's email-id
EMAIL_HOST_PASSWORD = #password associated with above email-id

In the above code, EMAIL_HOST_USER = ‘xabc6457@gmail.com’ and


EMAIL_HOST_PASSWORD = ‘xyz123abc@’ are the lines where you need to add the sender’s
mail id and password. xabc6457@gmail.com and xyz123abc@ are just examples.
Now to use this in our application, move to views.py and add these lines at the top section as
below.

from django.conf import settings


from django.core.mail import send_mail
Generally, emails are sent to the users who signup right? So, in the signup view function, add these
lines.

subject = 'welcome to GFG world'


message = f'Hi {user.username}, thank you for registering in geeksforgeeks.'
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email, ]
send_mail( subject, message, email_from, recipient_list )
Now we will understand what exactly is happening. Here,
 subject refers to the email subject.
 message refers to the email message, the body of the email.
 email_from refers to the sender’s details. This takes the EMAIL_HOST_USER from
settings.py file, where you added those lines of code earlier.
 recipient_list is the list of recipients to whom the mail has to be sent that is, whoever
registers to your application they receive the email.
 send_mail is an inbuilt Django function that takes subject, message, email_from, and
recipient’s list as arguments, this is responsible to send emails.
After these extra lines of code has been added to your project, you can send emails now. But if you
are using Gmail, then the first time you make these changes in your project and run, you might
get SMTP error.

To correct that-

1-Go to the Google account registered with the sender’s mail address and select Manage your
account

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.

from django import forms


class StudentForm(forms.Form):
firstname = forms.CharField(label="Enter first name",max_length=50)
lastname = forms.CharField(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.

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


<input type="text" name="firstname" required maxlength="50" id="id_firstname" />
<label for="id_lastname">Enter last name:</label> <input type="text" name="lastname" require
d 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 TextInput Whatever you've given as


CharField(**kwargs) empty_value.

ChoiceField class Select '' (an empty string)


ChoiceField(**kwargs)

DateField class DateInput None


DateField(**kwargs)

DateTimeField class DateTimeInput None


DateTimeField(**kwarg
s)

DecimalField class NumberInput None


DecimalField(**kwargs)

EmailField class EmailInput '' (an empty string)


EmailField(**kwargs)
FileField class ClearableFileInp None
FileField(**kwargs) ut

ImageField class ClearableFileInp None


ImageField(**kwargs) ut

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.

from django import forms


class StudentForm(forms.Form):
firstname = forms.CharField(label="Enter first name",max_length=50)
lastname = forms.CharField(label="Enter last name", max_length = 100)

Put this code into the forms.py file.

Instantiating Form in Django

Now, we need to instantiate the form in views.py file. See, the below code.

// views.py

from django.shortcuts import render


from myapp.form import StudentForm

def index(request):
student = StudentForm()
return render(request,"index.html",{'form':student})

Passing the context of form into index template that looks like this:

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>

Provide the URL in urls.py

from django.contrib import admin


from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
]

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

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.

// models.py

from django.db import models


class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=100)
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"

Now, create a form which contains the below code.

// forms.py

from django import forms


from myapp.models import Employee

class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = "__all__"

Instantiate the form

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

//views.py

def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
return redirect('/')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})

Index template that shows form and errors.

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form method="POST" class="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>

Start server and access the form.

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


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 django.contrib.staticfiles module helps to manage them.

Django Static (CSS, JavaScript, images) Configuration

1. Include the django.contrib.staticfiles in INSTALLED_APPS.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]

2. Define STATIC_URL in settings.py file as given below.

STATIC_URL = '/static/'

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

{% 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.

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
</head>
<body>
<img src="{% static '/wallpaper.jpeg' %}" alt="My image" height="300px" width="700px"/>
</body>
</html>

//urls.py

from django.contrib import admin


from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
]

//views.py

1. def index(request):
return render(request,'index.html')

Run the server by using python manage.py 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 index.html file.

{% load static %}
<script src="{% static '/js/script.js' %}"
// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<script src="{% static '/js/script.js' %}" type="text/javascript"></script>
</head>
<body>
</body>
</html>

// script.js

alert("Hello, Welcome to Javatpoint");

Now, our project structure looks like this:

Run the server by using python manage.py 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 index.html file.

{% load static %}
<link href="{% static 'css/style.css' %}" rel="stylesheet">

After that create a directory CSS and file style.css which contains the following code.

// style.css

h1{
color : red;
}
Our project structure looks like this:

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<link href="{% static 'css/style.css' %}" rel="stylesheet">
</head>
<body>
<h1>Welcome to Javatpoint</h1>
</body>
</html>

Run the server by using python manage.py runserver command.

After that access the template by entering localhost:8000/index URL, and it will produce the
following output to the browser.

You might also like