0% found this document useful (0 votes)
45 views10 pages

Chapter 5_Web Development Using Django

Uploaded by

Jayshree Solunk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views10 pages

Chapter 5_Web Development Using Django

Uploaded by

Jayshree Solunk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Unit 5: Web Development using Django

5.1 Introduction to Web Development and Django:

Web Development:

Web development refers to the process of creating, building, and maintaining websites and
web applications that run on the internet or intranet. It involves various tasks, from designing
a website's user interface to implementing its functionality and ensuring it performs well.

Web development includes the following aspects:

 Frontend Development: Focuses on the visual and interactive elements of a website,


such as layout, design, and user interaction.
 Backend Development: Handles the server-side logic, database management, and
application performance.
 Full-Stack Development: Involves both frontend and backend development.

Web development is the backbone of the modern internet, enabling businesses, organizations,
and individuals to create a digital presence and provide services to users worldwide.

Key Components of Web Development:

Frontend (Client-Side) Development : The part of a website users interact with directly,
often referred to as the UI (User Interface).

 Languages and Technologies:


o HTML (HyperText Markup Language): Structures web content.
o CSS (Cascading Style Sheets): Styles the appearance of web pages.
o JavaScript: Adds interactivity and dynamic behavior.
 Frameworks and Libraries:
o CSS frameworks: Bootstrap, Tailwind CSS.
o JavaScript frameworks/libraries: React, Angular, Vue.js.

Backend (Server-Side) Development : The backend processes and delivers the data
requested by the frontend.

 Languages and Technologies:


o Python, Ruby, PHP, Java, Node.js.
 Frameworks:
o Django (Python), Flask (Python), Express (Node.js), Spring (Java).
 Databases:
o SQL-based: MySQL, PostgreSQL.
o NoSQL-based: MongoDB, Firebase.
 APIs (Application Programming Interfaces):
o Facilitate communication between frontend and backend.
Database Management: Databases store, retrieve, and manage application data. Web
developers use database management systems (DBMS) to handle large volumes of data
efficiently.

Introduction to Django Framework

Django is a high-level Python web framework that enables developers to build robust,
scalable, and secure web applications rapidly. Known for its "batteries included"
philosophy, Django comes with a wide range of built-in features that simplify web
development tasks like authentication, database management, and URL routing.

What is Django?

Django is an open-source web framework developed to follow the Model-View-Template


(MVT) architectural pattern. It was first released in 2005 by Adrian Holovaty and Simon
Willison. Django’s primary goal is to help developers take applications from concept to
completion as quickly as possible.

Key Features of Django

1. Scalability:
o Ideal for small projects and enterprise-level applications alike.
2. Security:
o Protects against common vulnerabilities like SQL injection, cross-site
scripting (XSS), and cross-site request forgery (CSRF).
3. ORM (Object-Relational Mapping):
o Simplifies database interactions using Python classes instead of SQL queries.
4. Built-in Admin Interface:
o Automatically generates a web-based admin panel to manage application data.
5. Rapid Development:
o Streamlines repetitive tasks with pre-built tools.
6. Extensibility:
o Provides flexibility to integrate third-party packages or custom functionalities.

Django’s MVT Architecture

Django uses the Model-View-Template (MVT) pattern to separate concerns within a web
application.

 Model:

 Represents the data structure of the application.


 Interacts with the database using Django's ORM.
 Example:

from django.db import models


class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
 View:

 Handles the business logic and communicates with the model and template.
 Example:

from django.shortcuts import render


def home(request):
return render(request, 'home.html', {'message': 'Welcome to Django!'})

 Template:

 Defines the presentation layer (HTML with placeholders for dynamic data).
 Example (home.html):

<h1>{{ message }}</h1>

Setting Up Django

 Python (>= 3.x).


 Install Django: >> pip install django
 >> pip freeze

Creating a new Project:

Cmd:

D:\django-projects>> django-admin

D:\django-projects>> django-admin startproject DemoProject

DemoProject folder create with manage.py file

Run Project or starting development server:

D:\django-projects\DemoProject>> python manage.py runserver

Copy URL with port number and paste on browser- web application run
Project Folder structure:

Creating URLs and View:

Right click on internal Project folder-> New file-> views.py

Views.py

Import HttpResponse: It display user response on browser (display text msg on browser)

http:\\localhost:8000\about-us/

from django.http import HttpResponse

def about_us(request):
return HttpResponse("Welcome in Python Django")

def courese(request):
return HttpResponse("MCA")

To Call function on URL-need to create URL in urls.py file

Step1: import view file

Step2:add path

Urls.py:

from TestProject import views

urlpatterns = [
path('admin/', admin.site.urls),
path('about/', views.about_us),
path('course/', views.course),
]

Browser: http://127.0.0.1:8000/about/

Welcome in python Django


Creating Dynamic URL or route :
3 types supported here to send data-

Int-> 2

String -> hello

Slug -> hello-dyp-aa (valid- hello, hello123, hello-123 invalid: hello@dyp)

Urls.py:

# path('course/<int:courseid>', views.courseDetails)
# path('course/<str:courseid>', views.courseDetails)
# path('course/<slug:courseid>', views.courseDetails)

#for any generic type


path('course/<courseid>', views.courseDetails)

Views.py

def courseDetails(request,courseid):
return HttpResponse(courseid)

Browser: http://127.0.0.1:8000/course/2 ----int


2
Browser: http://127.0.0.1:8000/course/Hello ------str
Hello
Browser: http://127.0.0.1:8000/course/Hello-dyp-pune ----slug
Hello-dyp-pune

Render HTML template as Response:


Create new folder in Project Structure- templates
templates-> index.html
<html>
<head>
<title>Home Page</title>
<style>
.main{
width:500px;
background-color:red;
color:white;
font-size:30px;
padding:20px;
}
</style>
</head>
<body>
<div class="main">
<h1>Hello,Welcome in Django</h1>
</div>
</body>
</html>

Settings.py
TEMPLATES = [
{
'DIRS': [BASE_DIR,"templates"],

}
]
Argument 1: BASE_DIR : provides project folder path
Argument 2:template folder name

Urls.py
from TestProject import views

urlpatterns = [
path('admin/', admin.site.urls),
path('',views.HomePage), #1st argument empty- open home page direct
path('about/', views.about_us),
]

Views.py : render () : open or render html pages


from django.http import HttpResponse
from django.shortcuts import render

def HomePage(request):
return render(request,"index.html")

def about_us(request):
return HttpResponse("Welcome in Python Django")
Passing Data from Django view to template: Dynamic
Views page- render(request,htmlpage,data)

Index page : to display data using key name (binding) – {{key}}

Views.py
from django.shortcuts import render

def HomePage(request):
data={
'title':'Home Page',
'bdata':'welcome in DYP | Pune'
}
return render(request,"index.html",data)

index.html
<html>
<head>
<title>{{title}}</title>
<style>
.main{
width:800px;
background-color:red;
color:white;
font-size:30px;
padding:20px;
}
</style>
</head>
<body>
<div class="main">
<h1>{{bdata}}</h1>
</div>
</body>
</html>
Django Template using forloop:
For loop provides following properties:
forloop.counter : starts index from 1
forloop.counter0 : starts index from 0
forloop.revcounter : reverse index upto 1
forloop.revcounter0 : reverse index upto 0
forloop.first : first element active- True, remaining false
forloop.last : last element active- True, remaining false

Views.py
from django.shortcuts import render

def Home_page(request):
data={
'title':'Home Page',
'bdata':'Welocme in Django',
'course_list':['Python','Java','PHP'],
'stud_details':[{'name':'AAA','age':23},
{'name':'BBB','age':25},
{'name':'CCC','age':24} ],
'num':[12,3,4,56,67,45]
}
return render(request,"index.html",data)

index.py
<body>
<div class="main">
<h1>{{bdata}}</h1>
{% for n in course_list %}
<div>{{forloop.counter0}} {{n}}</div>
{% endfor %}

{% for n1 in num %}
{% if n1>20 %}
<div>{{n1}}</div>
{% endif %}
{% endfor %}
</div>
<table border='1' cellpadding='10'>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
{% for d in stud_details %}
<tr>
<td>{{d.name}}</td>
<td>{{d.age}}</td>
</tr>
{% endfor %}
</table>
</body>

Managing static Files: images,javascript,CSS


Create new folder to store static data: static

Static -> css,images,JS

Settings.py

STATICFILES_DIRS=[
BASE_DIR,"static"
]

In html file give path like:

<link href="/static/default.css" rel="stylesheet" type="text/css"


media="all" />

OR
{% load static %}
.
.
<link href="{% static ‘default.css’ %} " rel="stylesheet" type="text/css"
media="all" />

 Same for images and JS files


Header and footer:
{% include “header.html” %}
….
….
{% include “footer.html” %}

You might also like