0% found this document useful (0 votes)
30 views39 pages

About Djandgo

This document provides an introduction to Django, a web framework for building dynamic web applications using Python. It discusses the advantages of using frameworks over traditional CGI scripting, explains the MVC design pattern, and outlines the history and evolution of Django. Additionally, it covers installation, creating virtual environments, setting up a Django project, and creating views and URL configurations for dynamic content.

Uploaded by

brsmce007
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)
30 views39 pages

About Djandgo

This document provides an introduction to Django, a web framework for building dynamic web applications using Python. It discusses the advantages of using frameworks over traditional CGI scripting, explains the MVC design pattern, and outlines the history and evolution of Django. Additionally, it covers installation, creating virtual environments, setting up a Django project, and creating views and URL configurations for dynamic content.

Uploaded by

brsmce007
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/ 39

FULLSTACK

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

 And an HTML template


 Separation of concerns:
 models.py: Describes the database table using a Python
class (model).
 Enables creating, retrieving, updating, and deleting records using
Python instead of repetitive SQL.
 views.py: Contains business logic for the page.
 Example: latest_books() function, called a view.
 urls.py: Specifies which view handles a given URL pattern.
 Example: URL /latest/ calls latest_books().
 latest_books.html: HTML template for the page design.
 Uses a template language (e.g., {% for book in book_list %}).
 Model-View-Controller (MVC) Pattern:
 Model: Defines and accesses data.
 View: User interface design.
 Controller: Request-routing logic.

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

 This is how Django was created!


 Django’s Sweet Spot:
 Originally built for content-heavy, dynamic sites (e.g., Amazon,
Craigslist, The Washington Post).
 Particularly suited for dynamic, database-driven information.
 Effective for building all types of dynamic websites, not limited
to content-heavy ones.
 Open-Source Community:
 Extracted from real-world code, solving actual Web-
development problems.
 Actively improved daily by developers with hands-on
experience.
 Motivated by the desire to save time, improve performance,
and enjoy development work.
 Developers "eat their own dog food," meaning they use
Django for their own projects.
INSTALLING 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.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

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


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:

 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

 Django creates a folder named members in my project, with this


content:
VIEWS
 Django views are Python functions that takes http requests and returns
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:

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

 Defining the View Function:


 Next, you define a function called hello, which is the view function.

 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:

 If the server is not running, navigate to the /my_tennis_club folder and


execute this command in the command prompt:
 py manage.py runserver

 In the browser window, type 127.0.0.1:8000/members/ in the address bar.


 Output in the next slide..
YOUR SECOND VIEW: DYNAMIC CONTENT
 "Hello world" View Recap:
 It demonstrates Django basics, but it’s not dynamic—the content is always the same.
 Every time you visit /hello/, you see the same page, making it similar to a static HTML
file.
 Next Step: Dynamic Web Page:
 Let’s create a dynamic view that displays the current date and time.
 This example doesn't require a database or user input—just the output from the
server's clock.
 This view demonstrates:
 Calculating the current date and time.
 Returning an HttpResponse with that value.

 Using Python’s ‘datetime’ Module:

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

 Complete views.py Example:


 Changes to views.py for current_datetime View
 Importing datetime:
 Added import datetime at the top of the module to calculate dates.

 New current_datetime Function:


 Calculates the current date and time as a datetime.datetime object, stored in the
variable now.
 Constructing the HTML Response:
 The HTML response is created using Python’s format-string capability:
 The %s is a placeholder, replaced with the value of now.
 Although now is a datetime.datetime object, %s converts it to a string.
 Example result:
 "It is now 2008-12-13 14:09:39.002731.“

 Returning the Response:


 The view returns an HttpResponse containing the generated HTML—just like in
the hello function.
 Adding the URLpattern for current_datetime:
 Update urls.py:
 Add a new pattern to tell Django which URL should handle the current_datetime
view.
 Example: Use /time/ as the URL.
 Two Key Changes:
 Import the current_datetime
function.
 Add a URLpattern that maps the
URL /time/ to the
current_datetime view.
 Test It:
 With the view and URLconf
updated, run the server and
visit:http://127.0.0.1:8000/time/
 You should see the current date
and time displayed.
URLCONFS AND LOOSE
COUPLING IN DJANGO
 Loose Coupling Philosophy:
 A software approach where components are interchangeable.
 Changes to one part of the code have little or no impact on other parts.

 URLconfs: An Example of Loose Coupling:


 In Django, URL definitions and view functions are loosely coupled.
 The URL and the view logic are kept separate, making it easier to modify either
independently. by simply updating the URLconf:
 Example:
 If you wanted to change the URL from
/time/ to /current-time/, you’d only need to
update the URLconf.
 You could also change the logic of
current_datetime without modifying its
URL.
 Multiple URLs for the Same View:
 You can expose the same view function at
different URLs by simply updating the
ERRORS IN DJANGO
 So far, we’ve defined only one
URLpattern: /time/ and /hello/.
 What happens when a different URL is
requested?
 Example URLs:
 /hello/
 /does-not-exist/
 / (site root)
 Result: “Page not found” message (404 Error).
 Understanding the 404 Error Page in Django:
 Information provided on the 404 page:
 Which URLconf Django used.
 List of all URL patterns in that URLconf.
 Helps identify why the URL triggered a 404 error.
 Debug Mode in Django
 Sensitive information:
 404 page shows detailed info for developers.
 Only displayed when the project is in debug mode.
 Production Mode:
 If debug mode is off, a different response is shown.
 Debug mode is enabled by default in new Django projects.
 Learn to deactivate it later for production sites.
DJANGO’S PRETTY ERROR PAGES
 Admire the Web application created so far, and now deliberately break it to
see Django's error handling.
 Introducing an error: Modify views.py by converting offset in to a string in
the hours_ahead view.
 Result:
 Start the development server.
 Navigate to /time/plus/3/.
 Django displays an error page with detailed information.

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

You might also like