0% found this document useful (0 votes)
13 views

Introduction to Django

Uploaded by

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

Introduction to Django

Uploaded by

pshiv09098
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to

Django
Django is a back-end server side web framework.

Django is free, open source and written in Python.

Django makes it easier to build web pages using Python.

Django is a Python framework that makes it easier to


create web sites using Python.
How does Django Work?
Django follows the MVT design pattern (Model View
Template).
• Model - The data you want to present, usually data
from a database.
• View - A request handler that returns the relevant
template and content - based on the request from
the user.
• Template - A text file (like an HTML file) containing
the layout of the web page, with logic on how to
display the data.
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM),
which is a technique designed to make it easier to work with databases.

The most common way to extract data from a database is SQL. One problem
with SQL is that you have a pretty good understanding of the database
structure to be able to work with it.

Django, with ORM, makes it easier to communicate with the database,


without having to write complex SQL statements.

The models are usually located in a file called models.py.


View
A view is a function or method that takes http requests as arguments, imports the
relevant model(s), and finds out what data to send to the template, and returns the
final result.

The views are usually located in a file called views.py.


Template
A template is a file where you describe how the result should
be represented.
Templates are often .html files, with HTML code describing
the layout of a web page, but it can also be in other file
formats to present other results, but we will concentrate
on .html files.
Django uses standard HTML to describe the layout, but uses
Django tags to add logic:

<h1>My Homepage</h1>
<p>My name is {{ firstname }}.</p>

The templates of an application is located in a folder named templates.


URLs
Django also provides a way to navigate around the different pages in a website.
When a user requests a URL, Django decides which view it will send it to.
This is done in a file called urls.py.

When you have installed Django and created your first Django web
application, and the browser requests the URL, this is basically what happens:
1.Django receives the URL, checks the urls.py file, and calls the view that
matches the URL.
2.The view, located in views.py, checks for relevant models.
3.The models are imported from the models.py file.
4.The view then sends the data to a specified template in the templates folder.
5.The template contains HTML and Django tags, and with the data it returns
finished HTML content back to the browser.
Django can do a lot more than this and are the basic steps in a simple web
application made with Django.
Django Getting Started
Django Requires Python

To check if your system has Python installed, run this command in the command prompt:
python --version

If Python is installed, you will get a result with the version number, like this
Python 3.13.2

PIP
To install Django, you must use a package manager like PIP, which is included in Python from
version 3.4.
To check if your system has PIP installed, run this command in the command prompt:
pip --version

If PIP is installed, you will get a result with the version number.
For me, on a windows machine, the result looks like this:
pip 24.3.1 from C:m Files\WindowsApps\PythonVersion\Lib\site-packages\pip (python 3.13)
Django - Create Virtual Environment
Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and one way to
manage a virtual environment is venv, which is included in Python.
The name of the virtual environment is your choice, we will call it myworld.
Type the following in the command prompt, remember to navigate to where you want to create your
project:
python -m venv myworld
This will set up a virtual environment, and create a folder named "myworld"
with subfolders and files, like this:
• myworld
Include
Lib
Scripts
.gitignore
pyvenv.cfg
Then you have to activate the environment, by typing this command:
myworld\Scripts\activate.bat
Once the environment is activated, you will see this result in the command prompt :
(myworld) C:\Users\Your Name>
Install Django
• Now, that we have created a virtual environment, we are ready
to install Django.
python -m pip install Django
Check Django Version

You can check if Django is installed by asking for its version


number like this:
(myworld) C:\Users\Your Name>django-admin --version
Now you are ready to create a Django project in a virtual
environment on your computer.
Django Create Project
My First Project
Once you have come up with a suitable name for your Django project, like mine: my_tennis_club, navigate to
where in the file system you want to store the code (in the virtual environment), I will navigate to
the myworld folder, and run this command in the command prompt:

django-admin startproject my_tennis_club

Django creates a my_tennis_club folder on my computer, with this content:

my_tennis_club
manage.py
my_tennis_club/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
Run the Django Project
Now that you have a Django project, you can run it, and see what it looks like in a browser.

Navigate to the /my_tennis_club folder and execute this command in the command prompt:

python manage.py runserver

Which will produce this result:

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations
for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
March 19, 2025 - 14:19:38
Django version 5.1.7, using settings 'my_tennis_club.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Open a new browser window and type 127.0.0.1:8000 in the address bar.
Django Create App
• An app is a web application that has a specific meaning in your project, like a home page, a contact form, or
a members database.
let's just create a simple Django app that displays "Hello World!".

Create App
I will name my app members.
Start by navigating to the selected location where you want to store the app, in my case
the my_tennis_club folder, and run the command below.
If the server is still running, and you are not able to write commands, press [CTRL] [BREAK], or [CTRL] [C] to
stop the server and you should be back in the virtual environment.
python manage.py startapp members
Django creates a folder named members in my project, with this content:
my_tennis_club
manage.py
my_tennis_club/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Django Views
Django views are Python functions that take http requests
and return http response, like HTML documents.
A web page that uses Django is full of views with different
tasks and missions.
Views are usually put in a file called views.py located on
your app's folder.
There is a views.py in your members folder that looks like
this:
my_tennis_club/members/views.py:
from django.shortcuts import render
# Create your views here.

Find it and open it, and replace the content with this:
my_tennis_club/members/views.py:
from django.shortcuts import render
from django.http import HttpResponse

def members(request):
return HttpResponse("Hello world!")
This is a simple example on how to send a response back to the
browser.
Django URLs my_tennis_club/my_tennis_club/urls.py:
Create a file named urls.py in the same from django.contrib import admin
folder as the views.py file, and type this from django.urls import include, path
code in it: urlpatterns = [ path('',
my_tennis_club/members/urls.py: include('members.urls')), path('admin/',
from django.urls import path
from . import views urlpatterns = [ admin.site.urls), ]
path('members/', views.members,
name='members’),
]
The urls.py file you just created is
specific for the members application. We If the server is not running, navigate to
have to do some routing in the root the /my_tennis_club folder and execute
directory my_tennis_club as well. This may this command in the command prompt:
seem complicated, but for now, just follow python manage.py runserver
the instructions below. In the browser window, type
There is a file called urls.py on 127.0.0.1:8000/members/ in the address
the my_tennis_club folder, open that file and bar.
add the include module in
the import statement, and also add
a path() function in the urlpatterns[] list,
with arguments that will route users that
comes in via 127.0.0.1:8000/.
Modify the View
Django Templates Open the views.py file in
the members folder, and replace its content
Create a templates folder inside with this:
the members folder, and create a HTML file my_tennis_club/members/views.py:
named myfirst.html.
from django.http import HttpResponse
The file structure should be like this: from django.template import loader
my_tennis_club def members(request):
manage.py template =
loader.get_template('myfirst.html’)
my_tennis_club/ return HttpResponse(template.render())
members/ Change Settings
To be able to work with more complicated stuff than "Hello
templates/
World!", We have to tell Django that a new app is created.
myfirst.html This is done in the settings.py file in
the my_tennis_club folder.
my_tennis_club/members/ Look up the INSTALLED_APPS[] list and add the members app like
templates/myfirst.html: this:
my_tennis_club/my_tennis_club/
<!DOCTYPE html> settings.py:
<html> INSTALLED_APPS = [
'django.contrib.admin’,
<body> 'django.contrib.auth’,
<h1>Hello World!</h1> 'django.contrib.contenttypes’,
<p>Welcome to my first Django project! 'django.contrib.sessions’,
</p> 'django.contrib.messages’,
</body> 'django.contrib.staticfiles’,
</html> 'members’
]
Then run this command:
python manage.py migrate
Start the server by navigating to the /my_tennis_club folder and
execute this command:
python manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address
bar.
Django Models
• A Django model is a table in your database.
• Now we will see how Django allows us to work with data, without having to
change or upload files in the process.
• In Django, data is created in objects, called Models, and is actually tables in a
database.
Create Table (Model)
To create a model, navigate to the models.py file in the /members/ folder.
Open it, and add a Member table by creating a Member class, and describe the table
fields in it:
my_tennis_club/members/models.py:
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
SQLite Database
When we created the Django project, we got an empty SQLite database.
It was created in the my_tennis_club root folder, and has the filename db.sqlite3.
By default, all Models created in the Django project will be created as tables in this database.
Django creates a file describing the changes
Migrate and stores the file in the /migrations/ folder:
my_tennis_club/members/migrations/
Now when we have described a Model in
0001_initial.py:
the models.py file, we must run a # Generated by Django 5.1.7 on 2025-03-29 11:39
command to actually create the table in from django.db import migrations, models
the database. class Migration(migrations.Migration):
initial = True
Navigate to the /my_tennis_club/ folder
dependencies = [
and run this command: ]
operations = [
python manage.py makemigrations migrations.CreateModel(
name='Member’,
members fields=[
('id',
Which will result in this output: models.BigAutoField(auto_created=True,
primary_key=True, serialize=False,
Migrations for 'members': verbose_name='ID')),
('firstname',
members\migrations\0001_initial.py models.CharField(max_length=255)),
- Create model Member ('lastname',
models.CharField(max_length=255)),
(myworld) C:\Users\Your Name\myworld\ ],
),
my_tennis_club> ]
Django inserts an id field for your tables, which is an auto increment number (first record gets the
value 1, the second record 2 etc.), this is the default behavior of Django, you can override it by
describing your own id field.
The table is not created yet, you will have to run one more command, then Django will create and
execute an SQL statement, based on the content of the new file in the /migrations/ folder.

Run the migrate command:


python manage.py migrate
Which will result in this output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes,
members, sessions
Running migrations:
Applying members.0001_initial... OK

(myworld) C:\Users\Your Name\myworld\


my_tennis_club>

Now you have a Member table in you database!


View SQL
As a side-note: you can view the SQL statement that were executed from
the migration above. All you have to do is to run this command, with the
migration number:
python manage.py sqlmigrate members 0001
Which will result in this output:
BEGIN;
--
-- Create model Member
--
CREATE TABLE "members_member" ("id" integer NOT NULL PRIMARY KEY
AUTOINCREMENT, "firstname" varchar(255) NOT NULL, "lastname"
varchar(255) NOT NULL);
COMMIT;
Django Insert Data
• Add Records >>> from members.models import Member
We will use the Python interpreter (Python Hit [enter] and write this to look at the empty
shell) to add some members to it. Member table:
To open a Python shell, type this command:
python manage.py shell >>> Member.objects.all()
Now we are in the shell, the result should be
This should give you an empty QuerySet object,
something like this:
like this:
Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4
2025, 15:23:48) [MSC v.1942 64 bit <QuerySet []>
(AMD64)] on win32
Type "help", "copyright", "credits" or A QuerySet is a collection of data from a
"license" for more information. database.
(InteractiveConsole)
>>> Add a record to the table, by executing these
At the bottom, after the three >>> write the two lines:
following:
>>> member = Member(firstname='Emil',
lastname='Refsnes')
>>> member.save()
Execute this command to see if the Member table got a member:
>>> Member.objects.all().values()

the result will look like this:


• <QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'}]>

Add Multiple Records


You can add multiple records by making a list of Member objects, and execute .save() on
each entry:
>>> member1 = Member(firstname='Tobias', lastname='Refsnes')
>>> member2 = Member(firstname='Linus', lastname='Refsnes')
>>> member3 = Member(firstname='Lene', lastname='Refsnes')
>>> member4 = Member(firstname='Stale', lastname='Refsnes')
>>> member5 = Member(firstname='Jane', lastname='Doe')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
... x.save()
...
>>>
Hit [enter] one more time at the end to exit the for loop.
Now, if you run this command:
• >>> Member.objects.all().values()

you will see that there are 6 members in the Member table:
Update Records
To update records that are already in the database, we first
have to get the record we want to update:
>>> from members.models import Member
>>> x = Member.objects.all()[4]
x will now represent the member at index 4, which is "Stale
Refsnes", but to make sure, let us see if that is correct:
>>> x.firstname
This should give you this result:
'Stale'
Now we can change the values of this record:
>>> x.firstname = "Stalikken"
>>> x.save()
Execute this command to see if the Member table got updated:
>>> Member.objects.all().values()
Delete Records
To delete a record in a table, start by getting the record you
want to delete:
>>> from members.models import Member
>>> x = Member.objects.all()[5]
x will now represent the member at index 5, which is "Jane Doe",
but to make sure, let us see if that is correct:
>>> x.firstname
This should give you this result:
'Jane'
Now we can delete the record:
>>> x.delete()
The result will be:
(1, {'members.Member': 1})
How to create a form using Django Forms ?

Django forms are an advanced set of HTML forms


that can be created using python and support all features
of HTML forms in a pythonic way. This post revolves
around how to create a basic form using various Form
Fields and attributes. Creating a form in Django is
completely similar to creating a model, one needs to
specify what fields would exist in the form and of what
type. For example, to input, a registration form one might
need First Name (CharField), Roll Number (IntegerField),
and so on.
Creating a form using Django
Forms
• Consider a project named formspro having an app named formsapp.
In your formsapp make a new file called forms.py where you would be making all your
forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it.

In your forms.py Enter the following,

from django import forms

# creating a form
class InputForm(forms.Form):

first_name = forms.CharField(max_length = 200)


last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
Let’s explain what exactly is happening, left side denotes the name of the field
and to the right of it, you define various functionalities of an input field
correspondingly. A field’s syntax is denoted as
Syntax :
Field_name = forms.FieldType(attributes)
Now to render this form into a view, move to views.py and create a home_view
as below.
from django.shortcuts import render
from .forms import InputForm

# Create your views here.


def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "home.html", context)
In view, one needs to just create an instance of the form class created above in
forms.py. Now let’s edit templates > home.html
<form action = "" method = "post">
{% csrf_token %}
{{form }}
<input type="submit" value=Submit">
Middleware in Django
In Python Django, middleware is a framework that
provides a method to process requests and responses globally
before they are processed by the view or after they leave the
view. Middleware components are designed so that they remain
between the web server and the view, allowing us to perform
various operations on requests and responses as they pass
through the Django application and web browser.
Working of Middleware
The working of middleware in Django involves a series of steps that are followed
when requests pass through the middleware components in the application.
Middleware is present between the web server and the view and hooks for pre-
processing and post-processing of requests and responses.
In summary, the middleware process in Django involves a series of processing
steps applied to requests and responses:
•Request Phase: The request is received by the server and then it passes
through each middleware component. If a response is returned from a
middlewareprocess_request, further processing is stopped.
•View Processing: When a request reaches the view, it processes it and
generates a response according to the code written inside the view function.
•Response Phase: WhenResponse passes through each middleware component
in reverse order. Modified response from each middleware is passed to the next
one. A modified response is sent back to the web server and then to the user.
This flow allows us to insert custom logic, security measures, session handling,
and other behaviors at various points of the request-response cycle in a modular
and reusable manner.
Types of Middleware in Django
Django's middleware can be divided into 2 types: built-in and custom.
Built-in Django Middleware: Django comes with a set of built-in
middleware classes. These are some of the most commonly used default
middleware classes in Django:
•SecurityMiddleware: It provides several security-related features such
as ensuring that all HTTP requests are redirected to HTTPS and is used to
add security headers to responses.
•SessionMiddleware: It helps in managing sessions for users. It enables
Django to handle session data, making it available to views and
templates.
•CommonMiddleware: Handles common operations such as URL
redirection (adding/removing "www" prefix), appending slashes to URLs.
•CsrfViewMiddleware: Enables protection against Cross-Site Request
Forgery (CSRF) attacks. It adds and verifies a CSRF token in POST
requests to protect against malicious requests from other sites.
•AuthenticationMiddleware: Adds the 'user' attribute to the request,
representing the currently logged-in user, if applicable. It also manages
session
The sessions framework can be used to provide persistent behavior for
anonymous users on the website. Sessions are the mechanism used by
Django for you to store and retrieve data on a per-site-visitor basis. Django
uses a cookie containing a unique session ID.
Django Sessions
• So let’s understand what a is session in Django and how to use sessions.
Django provides full support for anonymous sessions. The session
framework lets you store and retrieve arbitrary data on a per-site-visitor
basis. It keeps data on the server side and abstracts the sending and
receiving of cookies. Now that we have some basic understanding of the
session let’s figure out how to use session in Django.
How to use session in Django
First, enable Session in Django. To enable the session in Django, you will
need to make sure of two things in settings.py:
MIDDLEWARE_CLASSES has
‘django.contrib.sessions.middleware.SessionMiddleware’ activate
INSTALLED_APPS has ‘django.contrib.sessions’ added.
Django cookies
Cookies are small pieces of data that help store user-specific information on the client side. In Django,
managing cookies is a simple task that can be done using a few straightforward commands.

Cookies are essential for maintaining user sessions and preferences. They are used to store data such as login
information or user settings. Django provides easy methods to work with cookies, allowing to set and retrieve
them as needed.

Setting Cookies in Django


• To set a cookie in Django, we use the set_cookie method on an HttpResponse object. This method allows
you to define the cookie’s name, value, and optional parameters such as expiration time and domain. Here’s
how to set a basic cookie:
In this example:
•'my_cookie' is the name of the cookie.
•'cookie_value' is the value stored in the cookie.

from django.http import HttpResponse

def set_cookie_view(request):

response = HttpResponse("Cookie is set!")

response.set_cookie('my_cookie', 'cookie_value’)

return response

You might also like