Django
What is Django?
Django is a high-level Python Web framework that encourages rapid development and clean
pragmatic design.
Django makes it easier to build better web apps quickly and with less code.
History of Django
Django – Design Philosophies
Advantages of Django
Object-Relational Mapping (ORM) Support
Multilingual Support
Framework Support
Administration GUI
Development Environment
DJANGO MVC - MVT Pattern
MVC – Model, View, Controller
MVT – Model, View, Template
The main difference between the two patterns is that Django itself takes care of the Controller part
(Software Code that controls the interactions between the Model and View), leaving us with the
template.
The template is a HTML file mixed with Django Template Language (DTL).
Installation:
Step 1:
pip install django(One Time Installation)
Step 2:
django-admin startproject project1
Step 3:
Cd project1
Step 4:
python manage.py runserver
What is an 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.
-> We will create an app that allows us to list and register
members in a database.
-> Let’s just create a simple Django app that displays "Welcome
to the World of Django".
Navigate Inside the Project Folder:
py manage.py startapp members
Django 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.
Sample program:
App/views.py
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
return HttpResponse("Welcome to the World of Django ")
Django URLs
App/Urls.py
from django.urls import path
from . import views
urlpatterns = [
path('members/', views.members, name='members'),
]
Project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]
py manage.py runserver
Django Templates
Create a templates folder inside your app name
App/templates/Myfirst.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
Modify Views.py
from django.http import HttpResponse
from django.template import loader
def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change the Settings.py(Inside Project)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members',
]
py manage.py migrate
py manage.py runserver
Depth Knowledge on Django – Templates:
Key Features of Django Templates
Separation of Concerns:
Templates allow you to separate the presentation layer (HTML/CSS) from the business logic
layer (Python code).
Template Language:
Django templates use a simple language to define placeholders and control structures (like
loops and conditionals) within HTML.
Rendering Context:
Templates are rendered with a context, which is a dictionary mapping template variable
names to Python objects.
Reusable Templates:
Templates can be reused and extended using features like template inheritance, which allows
you to create a base template and extend it in other templates.
Basic Structure
A typical Django template contains placeholders for variables and tags for logic. Placeholders
are enclosed in double curly braces ({{ }}), and tags are enclosed in {% %}.
<!-- templates/example.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
<p>{{ content }}</p>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Template Tags and Filters
Template Tags:
Control the logic within the template, such as loops and conditionals.
Examples: {% if %}, {% for %}, {% block %}, {% extends %}.
Template Filters:
Modify the value of a variable before it is rendered.
Examples: {{ name|lower }}, {{ value|length }}, {{ date|date:"F d, Y" }}.
Using Templates in Django Views
To render a template in a view, you use the render function provided by Django.
# views.py
from django.shortcuts import render
def example_view(request):
context = {
'title': 'My Example Page',
'heading': 'Welcome to the Example Page',
'content': 'This is an example of using Django templates.',
'items': ['Item 1', 'Item 2', 'Item 3']
}
return render(request, 'example.html', context)
Template Inheritance
Django supports template inheritance, which allows you to define a base template and
extend it in child templates. This helps in maintaining a consistent layout across different
pages of your application.
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website Header</h1>
</header>
<div class="content">
{% block content %}{% endblock %}
</div>
<footer>
<p>My Website Footer</p>
</footer>
</body>
</html>
Child Template:
<!-- templates/child.html -->
{% extends "base.html" %}
{% block title %}Child Page Title{% endblock %}
{% block content %}
<h2>Child Page Content</h2>
<p>This is content specific to the child page.</p>
{% endblock %}
Simple Page Website:
from django.shortcuts import render
def home(request):
return render(request, 'main/home.html')
def about(request):
return render(request, 'main/about.html')
def contact(request):
return render(request, 'main/contact.html')
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
</nav>
<p>Welcome to the Home Page!</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<h1>About Page</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
</nav>
<p>Welcome to the About Page!</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
</head>
<body>
<h1>Contact Page</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
</nav>
<p>Welcome to the Contact Page!</p>
</body>
</html>
Django Models:
Django models are the essential components of the Django framework, designed to handle database
interactions. A model is a class that represents a database table, and each attribute of the class
corresponds to a column in that table. Django's Object-Relational Mapping (ORM) allows developers to
interact with the database using Python code, providing a high-level abstraction that simplifies database
operations.
Create Table (Model)
from django.db import models
class Batch(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
py manage.py makemigrations jaipurravi
py manage.py migrate
py manage.py shell
from jaipurravi.models import Batch
Batch.objects.all().values()
person1 = Batch(firstname='Deepu',lastname ='Deepak')
person1.save()
Batch.objects.all().values()
person2 = Batch(firstname='Annachi',lastname ='Vicky')
person3 = Batch(firstname = 'Mass',lastname = 'Keerthi')
person4 = Batch(firstname='Dio',lastname ='Dhamu')
person5 = Batch(firstname = 'Ravi',lastname= 'Satu Ji')
person_list = [person2,person3,person4,person5]
for i in person_list:
i.save()
Batch.objects.all().values()
Update :
---------
x = Batch.objects.all()[2]
x.firstname
x.firstname = "Don"
x.save()
Batch.objects.all().values()
Delete:
from members.models import Member
x = Batch.objects.all()[3]
x.delete()
models.py
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
py manage.py makemigrations jaipurravi
py manage.py migrate
py manage.py shell
from jaipurravi.models import Batch
x = Batch.objects.all()[0]
x.phone = 5551234
x.joined_date = '2023-01-05'
x.save()
Batch.objects.all().values()
Django Prepare Template
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li>{{ x.firstname }} {{ x.lastname }}</li>
{% endfor %}
</ul>
</body>
</html>
from django.http import HttpResponse
from django.template import loader
from .models import Member
def members(request):
mymembers = Batch.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
return HttpResponse(template.render(context, request))
all.html
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li><a href="details/{{ x.id }}">{{ x.firstname }} {{
x.lastname }}</a></li>
{% endfor %}
</ul>
</body>
</html>
from django.http import HttpResponse
from django.template import loader
from .models import Member
def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
return HttpResponse(template.render(context, request))
def details(request, id):
mymember = Member.objects.get(id=id)
template = loader.get_template('details.html')
context = {
'mymember': mymember,
return HttpResponse(template.render(context, request))
from django.urls import path
from . import views
urlpatterns = [
path('members/', views.members, name='members'),
path('members/details/<int:id>', views.details,
name='details'),
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
{% extends "master.html" %}
{% block title %}
My Tennis Club - List of all members
{% endblock %}
{% block content %}
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li><a href="details/{{ x.id }}">{{ x.firstname }} {{
x.lastname }}</a></li>
{% endfor %}
</ul>
{% endblock %}
Main Index Page
Our project needs a main page.
The main page will be the landing page when someone visits the root folder of
the project.
Main.html
{% extends "master.html" %}
{% block title %}
My Tennis Club
{% endblock %}
{% block content %}
<h1>My Tennis Club</h1>
<h3>Members</h3>
<p>Check out all our <a href="members/">members</a></p>
{% endblock %}
Views.py
def main(request):
template = loader.get_template('main.html')
return HttpResponse(template.render())
my_tennis_club/members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.main, name='main'),
path('members/', views.members, name='members'),
path('members/details/<int:id>', views.details,
name='details'),
Add Link Back to Main
The members page is missing a link back to the main page, so let us add that in
the all_members.html template, in the content block:
Example
my_tennis_club/members/templates/all_members.html:
{% extends "master.html" %}
{% block title %}
My Tennis Club - List of all members
{% endblock %}
{% block content %}
<p><a href="/">HOME</a></p>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li><a href="details/{{ x.id }}">{{ x.firstname }} {{
x.lastname }}</a></li>
{% endfor %}
</ul>
{% endblock %}
Page Not Found
If you try to access a page that does not exist (a 404 error), Django directs you
to a built-in view that handles 404 errors.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
my_tennis_club/members/templates/404.html:
<!DOCTYPE html>
<html>
<title>Wrong address</title>
<body>
<h1>Ooops!</h1>
<h2>I cannot find the file you requested!</h2>
</body>
</html>