Django_Notes
Django_Notes
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
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:
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
<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.
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 %}
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')
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.
class Batch(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
py manage.py migrate
py manage.py shell
Batch.objects.all().values()
person1.save()
Batch.objects.all().values()
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
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 migrate
py manage.py shell
x = Batch.objects.all()[0]
x.phone = 5551234
x.joined_date = '2023-01-05'
x.save()
Batch.objects.all().values()
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
</body>
</html>
def members(request):
mymembers = Batch.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
</body>
</html>
def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
mymember = Member.objects.get(id=id)
template = loader.get_template('details.html')
context = {
'mymember': mymember,
urlpatterns = [
path('members/details/<int:id>', views.details,
name='details'),
<!DOCTYPE html>
<html>
<head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
{% extends "master.html" %}
{% block title %}
{% endblock %}
{% block content %}
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% 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 %}
<h3>Members</h3>
{% endblock %}
Views.py
def main(request):
template = loader.get_template('main.html')
return HttpResponse(template.render())
my_tennis_club/members/urls.py:
urlpatterns = [
path('members/details/<int:id>', views.details,
name='details'),
Example
my_tennis_club/members/templates/all_members.html:
{% extends "master.html" %}
{% block title %}
{% endblock %}
{% block content %}
<p><a href="/">HOME</a></p>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
{% endblock %}
DEBUG = False
ALLOWED_HOSTS = ['*']
my_tennis_club/members/templates/404.html:
<!DOCTYPE html>
<html>
<title>Wrong address</title>
<body>
<h1>Ooops!</h1>
</body>
</html>