Professional Documents
Culture Documents
CO3 Django Material
CO3 Django Material
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 ?
Why Django?
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
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
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
urlpatterns = [
path('admin/', admin.site.urls),
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-
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.
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 ?
# get datetime
import datetime
# create a function
def geeks_view(request):
now = datetime.datetime.now()
# convert to string
# return response
return HttpResponse(html)
urlpatterns = [
path('', geeks_view),
To check how to make a basic project using MVT (Model, View, Template) structure of Django,
visit Creating a Project Django.
Types of 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.
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,
class GeeksModel(models.Model):
# fields of the model
description = models.TextField()
def __str__(self):
return self.title
After creating this model, we need to run two commands in order to create Database for the same.
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/
context ={}
context["dataset"] = GeeksModel.objects.all()
<div class="main">
{{ data.title }}<br/>
{{ data.description }}<br/>
<hr/>
{% endfor %}
</div>
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.
model = GeeksModel
urlpatterns = [
path('', GeeksList.as_view()),
<ul>
<hr/>
{% empty %}
{% endfor %}
</ul>
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
Let's open the file urls.py of the project and see the what it looks like:
// urls.py
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.
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
// urls.py
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.
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.
First, create a directory templates inside the project app as we did below.
// 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
//urls.py
1. path('index/', views.index),
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.
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
//views.py
//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.
{% 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.
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.
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.
After creating a model, register model into the INSTALLED_APPS inside settings.py.
For example,
INSTALLED_APPS = [
#...
'appname',
#...
]
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.
BooleanField class BooleanField(**options) A true/false field. The default form widget for
this field is a CheckboxInput.
TextField class TextField(**options) A large text field. The default form widget for
this field is a Textarea.
Field Options
Each field requires some arguments that are used to set column attributes. For example,
CharField requires mac_length to specify varchar database.
Field Particulars
Options
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.
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()
# 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
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:
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()
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.
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.
Passing a model:
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.
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:
Passing a URL:
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.
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
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.
The label is used to set HTML label of the component and max_length sets length of an input
value.
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.
Let's see a complete example to create an HTML form with the help of Django Form class.
Suppose we want to create a form to get Student information, use the following code.
Now, we need to instantiate the form in views.py file. See, the below code.
// views.py
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>
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:
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.
// models.py
// forms.py
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = "__all__"
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.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>
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.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
STATIC_URL = '/static/'
{% 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.
// 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
//views.py
1. def index(request):
return render(request,'index.html')
After that access the template by localhost:8000/index URL, and it will produce the following
output to the browser.
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
After that access the template by localhost:8000/index URL, and it will produce the following
output to the browser.
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>
After that access the template by entering localhost:8000/index URL, and it will produce the
following output to the browser.