About Djandgo
About Djandgo
DEVELOPMENT
(22IS503)
Introduction to Django
WHAT IS A WEB
FRAMEWORK?
Django is a prominent member of a new generation of Web frameworks.
To understand what is Web Framework, let’s consider the design of a Web application
written in Python without a framework.
Consider following HTML document:
WHAT IS A WEB
FRAMEWORK?
We should build a web application if we want to make the previous code
dynamic (which fetches books list from the database)
One of the simplest, most direct ways to build a Python Web app from
scratch is to use the Common Gateway Interface (CGI) standard, which was
a popular technique circa 1998.
Here’s a high-level explanation of how it works:
Create a Python script that outputs HTML,
Save the script to a Web server with a .cgi extension
Visit the page in your Web browser.
Here’s a sample Python CGI script that displays the ten most recently published books
from a database. Don’t worry about syntax details; just get a feel for the basic things it’s
doing.
Code Explained:
CGI code begins by printing a “Content-Type” line, followed by a blank
line.
Prints introductory HTML, connects to a database, and runs a query to
retrieve the latest ten book titles.
Generates an HTML list of book titles by looping over the results.
Prints closing HTML and closes the database connection.
Write-from-scratch approach is simple to understand, even for novice
developers.
Easy to deploy: save the code as a .cgi file, upload it to a Web server,
and access it via a browser.
Problems with this approach:
Database connection duplication: Multiple parts of an application may need
to connect to the database, leading to repeated code.
Solution: Refactor the database-connecting code into a shared function.
Boilerplate code: Printing the “Content-Type” line and closing the database
manually can lead to mistakes and reduced productivity.
Solution: Delegate setup and teardown tasks to common infrastructure.
Environment-specific issues: Reusing code in different environments may
require managing separate database configurations and passwords.
Web designer concerns: A designer with no coding experience could
accidentally crash the application when editing the page.
Solution: Separate the logic (retrieving data) from the HTML display to prevent
errors.
Web frameworks
Solve these problems by providing infrastructure for clean, maintainable code.
Django
A framework that handles these tasks, allowing developers to focus on writing
robust code without reinventing the wheel.
THE MVC DESIGN PATTERN
Let’s dive in with a quick example that demonstrates the difference
between the previous approach and a Web framework’s approach.
Here’s how you might write the previous CGI code using Django.
The first thing to note is that we split it over three Python files
models.py
views.py
urls.py
Advantages of MVC:
Loosely coupled components:
Change the URL without affecting implementation.
Update HTML without touching Python code.
Rename database tables with minimal code changes.
DJANGO'S HISTORY
Django grew organically from real-world applications built by a Web-
development team in Lawrence, Kansas, USA.
Created in 2003 by Adrian Holovaty and Simon Willison, web programmers
for the Lawrence Journal-World newspaper.
Development was driven by the need to build maintainable applications
quickly under journalism deadlines.
Released as open-source software in July 2005, named after jazz guitarist
Django Reinhardt.
Framework grew into a collaborative open-source project with tens of
thousands of users worldwide.
DJANGO’S EVOLUTION:
Classic Web Developer’s Path:
Write a Web application from scratch.
Repeat the process for another application.
Recognize shared code between projects.
Refactor code to share between applications.
Continue the process, eventually developing a framework.
If Python is installed, you will get a result with the version number, like this
Python 3.9.2
If you find that you do not have Python installed on your computer, then
you can download it for free from the following website:
https://www.python.org/
It is suggested to have a dedicated virtual environment for each Django
project, and in the next slide we will learn how to create a virtual
environment, and then install Django in it.
CREATE 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, in this tutorial we will
call it myworld.
Type the following in the command prompt, remember to navigate to
where you want to create your project:
py -m venv myworld.
This will set up a virtual
environment, and create a folder
named "myworld" with subfolders
and files, like this:
CREATE VIRTUAL
ENVIRONMENT
Then you have to activate the environment, by typing this command:
myworld\Scripts\activate
Once the environment is activated, you will see this result in the command
prompt:
Note: You must activate the virtual environment every time you open the
command prompt to work on your project.
INSTALLING DJANGO
Now, that we have created a virtual environment, we are ready to install
Django.
Note: Remember to install Django while you are in the virtual
environment!
Django is installed using pip, with this command:
You can check if Django is installed by asking for its version number like this:
CREATE A PROJECT
Lets name our the first Django project as : my_tennis_club.
Navigate to where in the file system you want to store the code (in the
virtual environment)
And run this command in the command prompt:
django-admin startproject my_tennis_club
Open a new browser window and type 127.0.0.1:8000 in the address bar.
Open a new browser window and type 127.0.0.1:8000 in the address bar.
CREATE A SAMPLE 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.
In this tutorial we will create an app that allows us to list and register
members in a database.
But first, let's just create a simple Django app that displays "Hello World!".
Lets create an App named “members”.
Start by navigating to the selected location where you want to store the
app
Lets do it in the my_tennis_club folder. Navigate to the folder and
run the command below.
py manage.py startapp members
Find it and open it, and replace the content with this:
STEP-BY-STEP CODE EXPLANATION:
Importing HttpResponse:
First, you import the class HttpResponse from the django.http module.
This class is used later in the code.
Parameter "request":
Each view function requires at least one parameter, typically named request.
This object contains information about the Web request and is an instance of
django.http.HttpRequest.
Although it's not used here, it must be the first parameter of the view.
Function Naming:
The name of the view function doesn't matter to Django.
We named it hello to indicate its purpose, but any name could be used.
The next section on "URLconf" will explain how Django finds this function.
Returning a Response:
The function simply returns an HttpResponse object with the text "Hello world".
URLS
What is a URLconf?
URLconf = Table of Contents for Django Websites:
It maps URLs to the view functions that should be called for those URLs.
How it Works:
It tells Django:
“For this URL, call this code. For that URL, call that code.”
Example:
When someone visits the URL /foo/, Django will call the view function foo_view().
This function lives in the Python module views.py.
URLS
Create a file named urls.py in the same folder as the views.py file, and type
this code in it:
The urls.py file you just created is specific for the members application. We
have to do some routing in the root directory my_tennis_club as well.
There is a file called urls.py on the my_tennis_club folder, open that file and
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/.
Then your file will look like this:
That’s simple enough, and it has nothing to do with Django. It’s just Python code.
CREATING A DJANGO VIEW
TO DISPLAY DATE AND TIME
Steps:
Use the datetime.datetime.now() function in a Django view.
Return an HttpResponse with the current date and time.
Error displayed:
TypeError: "unsupported type for timedelta hours component: str".
Django’s error page provides valuable debugging information, including the error
type and traceback.
MULTIPLICATION TABLE
GENERATOR
Objective: Create a view that accepts an integer and
returns the multiplication table for that number up to
10.
URL Pattern: /multiply/table/<int:number>/
Example:
/multiply/table/5/ returns the multiplication table for 5 (5x1
to 5x10).