Django - Getting Python in The Web - Lecture 2
Django - Getting Python in The Web - Lecture 2
Ahmed Moawad
Templates
{{ variable_name }}
library/index.html
<html>
<head> ... </head> Hello, Ahmed
<body>
<p> Hello, {{ name }} </p>
</body>
</html>
library/views.py
from django.shortcuts import render
def index(request):
return render(request, ‘library/index.html’, {‘name’: ‘Ahmed’})
Template Language
Tags
{% tag_name %}
library/index.html
<body>
<ul> • Forrest Gump
{% for m in movies %} • The Dark Knight
<li>{{ m }}</li> • Inception
{% endfor %}
</ul>
</body>
library/views.py
from django.shortcuts import render
def index(request):
names = [‘Forrest Gump’, ‘The Dark Knight’, ‘Inception’]
return render(request, ‘persons/index.html’,{‘names’: names})
Template Language
for statement
library/views.py
from django.shortcuts import render
def index(request):
names = []
return render(request, ‘persons/index.html’,{‘names’: names})
Template Language
if statement
library/views.py
from django.shortcuts import render
def index(request):
age = 14
return render(request, ‘persons/index.html’,{‘age’: age})
Template Language
Template Inheritance
student.html
{% extends “base.html” %}
library/index.html
<html>
Home Page
<body>
This is my home page …
<h2>{{ name | title }}</h2>
<p>{{ body | truncatewords:5 }}</p>
</body>
</html>
library/views.py
def index(request):
name = “home page”
body = “This is my home page. Please tell me your opinion.”
return render(request,‘index.html’,{‘name’: name, ‘body’: body})
Filters
Some useful Filters
Django Forms is a method to make a dynamic HTML Forms with its validation
library/forms.py
from django import forms
class AddBookForm(forms.Form):
title = forms.CharField(label=‘Title', max_length=100)
author = forms.CharField(label=‘Author', max_length=100)
is_free = forms.BooleanField(label=‘Is Free’)
date_published = forms.DateField(label=“Date Published”)
Forms
How to use
library/views.py
from .forms import AddBookForm
from django.shortcuts import render
def index(request):
form = AddBookForm()
return render(request, ‘library/index.html’,{‘form’: form})
library/index.html
<h2> Add New Book </h2>
<form method=“POST”> {% csrf_token %}
{{ form.as_p }}
</form>
Title
Author
Is Free
Forms
Form Class
Field Widget
CharField TextInput
EmailField EmailInput
IntegerField NumberInput
BooleanField CheckboxInput
ChoiceField Select
DateField DateInput
Forms
Fields Options
Field
required label initial
CharField
min_length max_length
IntegerField
min_value max_value
ChoiceField
choices
Forms
Example
library/views.py
def index_view(request):
if request.method=='POST':
form = AddBookForm(request.POST)
if form.is_valid():
# Add New Book to database
return HttpResponse("Mission Complete")
else:
form = AddBookForm()
return render(request,"library/add_book.html",{"form":form})
Views
More on Views
Know more about Django Views
More on Views
View Decorator
View Decorator is a method to make the view run under specific conditions
@require_http_methods(["GET"])
#or
@require_GET()
def my_view(request):
# Get Method Actions
pass
More on Views
Class-based Views
# views.py
from django.http import HttpResponse
from django.views import View
class MyView(View):
#method to be called if request Method is GET
def get(self, request):
return HttpResponse(‘GET result')
#Method to be called if request Method is GET
def post(self, request):
return HttpResponse(‘Post result')
# urls.py
...
urlpatterns = [ url(r'^about/$', MyView.as_view()) ]
More on Views
More Shortcuts
Generic Views
Generic Views
Intro
Generic Views is class-based Views that has a special purpose like listing & editing.
class BookView(DetailView):
model = Book
urlpatterns = [
url(r'^$', BookList.as_view()),
url(r'^/book/(?P<pk>[0-9]+)$', BookView.as_view()),
]
Generic Views
Views - template Map
More on URLs
Know more about Django URLs
Urls
URL Namespacing
namespace:url_name
library/urls.py
...
library:index
Http
reverse
reverse(view, args=None, kwargs=None)
or
# urls.py
urlpatterns = [
# view.py
def index(request):
url = reverse(‘posts’, args=[2,3])
#or url = reverse(‘library:posts’, args=[2,3])
return HttpResponseRedirect(url) # ‘/posts/2/comment/3’
Middleware
Middleware
Intro
process_view() process_template_response()
process_request () process_exception()
Middleware
Create Custom Middleware
library/middleware/dummymiddleware.py
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class DummyMiddleware(MiddlewareMixin):
def process_request(self,req):
req.dept = "OS"
return None
mysite/settings.py
MIDDLEWARE = [
# Other Middleware Classes,
“library.middleware.dummymiddleware.DummyMiddleware”
]
Middleware
Useful Built-in Middleware
settings.py
INSTALLED_APPS = [
# Other Apps,
“django.contrib.sessions”
]
MIDDLEWARE = [
# Other Middleware Classes,
“django.contrib.sessions.middleware.SessionMiddleware”
]
Sessions
How to use
request.session
views.py
def login(request,user_id):
#Setting Session item
request.session['member_id'] = user_id
return HttpResponse(“You are logged in”)
def view_profile(req):
#Getting Session item
if ‘member_id’ in req.session and req.session['member_id']:
return HttpResponse(“View Profile")
else:
return HttpResponse(“Please login to view ”)
Sessions
methods
request.session.get(key,default=None)
request.session.pop(key,default=__not_given)
request.session.clear()
request.session.set_expiry(value)
Sessions
settings
User
def any_view(request):
if request.user.is_authenticated():
# Do actions for Logged in Users
else:
# Do actions for Guests
Thank You