Intro To Framework, Server Side Programming With Django
Intro To Framework, Server Side Programming With Django
Intro to Framework,
Server Side
Programming with
Django
1
REVIEW
How did you code for
your previous labs-3?
2
How Did Your Previous Web Work?
Apakah ada HTTP Request?
Apakah ada HTTP Response?
3
How do we code in PPW
Add code to repository Gitlab Pipeline Remember
CI / CD gitlab-ci.yml?
Laptop B
REVIEW:
git add .
git commit -a -m “comment”
git push
The Internet
Accessing
the web page
[appname].herokuapp.com
Laptop A
HP XYZ HP ABC
4
Why Framework?
o Efficiency: provide basic building blocks
o Code reusing
o Separation concerns
o Community support
5
Server-Side Web Frameworks
o Django (Python)
o Express (Node.js)
o Ruby on Rails (Ruby)
o ASP.Net
o Laravel (PHP)
o etc...
6
Introduction to Django
Django is a Python web framework for rapid
development and clean. Django considers
main functionalities in the Web
Development that we only need to focus on
our app.
7
Lets appreciate them!
Fall 2003: Adrian Hovolaty and Simon
Willison began using Python to build
applications
Summer 2005: Jacob Kaplan-Moss joined and
the Framework was released
2008: released 1.0
8
Large Projects
Disqus
Pinterest
The Onion
etc.
See: djangosites.org
9
Why Django?
o Open source
o Ridiculously fast
o Fully loaded
o Reassuringly secure
o Exceedingly scalable
o Incredibly versatile
10
Installing Django
1. Install Python
2. Install a Python Virtual Environment
python -m venv env
env/Scripts/activate.bat (windows cmd only)
pip install -r requirements.txt
https://docs.djangoproject.com/en/2.1/
11
Virtual Environment
Can we run Django without using
VirtualEnv? YES! What is the different?
MY LAPTOP
C:\Project\DDP\ C:\Project\PPW\MyWeb
PC LAB
D:\Data\PPW\MyWeb
12
Model-View-Controller Pattern
Separate the businees logic and the
presentation layer
13
Model-View-Controller Pattern
14
Web Request / Response
Img from:
https://ruslanspivak.com
15
URL / URI
Img from:
https://ruslanspivak.com
16
How Webserver Works
Inside Your “Webserver” Request
Web Internet
Listen at some
host and port(s) Page
Parsed Request
Request
Page
Web
URL routing
ex: /search
ex: /home
ex: /login
17
How Django Framework Works
Your Webserver Environment
Request
Run
# manage.py Web
Page
Internet
Merged of html
template and Value Extracted arguments
Request
from process from Request
Page
Web
index.html views.py
18
Structure on Django Framework
Django is often referred to as an MTV
framework
o M stands for “Model”: the data access
layer
o T stands for “Template”: the presentation
layer
o V stands for “View”: the business logic
layer, the bridge between models and
templates.
19
Let’s rock the Django!!
Pronounce it: JENG-goh! :D
Start a project:
django-admin startproject [proj_label]
Build an app:
python manage.py startapp
[app_label]
20
Project
django-admin startproject [proj_label]
$ django-admin startproject draft_lab
21
Project
settings.py - configuration for the project
manage.py - command runner
urls.py - starting point to configure urls
22
How Django Webserver Works
Inside Your “Webserver” Request
Parsed Request
Request
URL routing: urls.py
Page
Web
ex: /search
ex: /
ex: /login
23
Project
Start up a development server:
$ python manage.py runserver
24
Applications
A project may consist of many apps
Built in apps: admin, auth, serving static files.
25
Applications
$ python manage.py startapp ppw
26
Applications
We have to tell django that it should use it.
Open draft_lab/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ppw',
]
27
Django urls
You access: http://[appname].herokuapp.com/ppw/
Django map ppw/ to a view by using regular
expression
cd draft_lab/urls.py
28
Django urls 1.11
draft_lab/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^ppw/', include('ppw.urls')),
]
https://docs.djangoproject.com/en/1.11/topics/http/urls/
29
Django urls 1.11
add ppw/urls.py
urlpatterns = [
url(r'^$', index, name='index'),
]
30
Django urls 2.1
draft_lab/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path(‘ppw/', include('ppw.urls')),
]
https://docs.djangoproject.com/en/2.1/topics/http/urls/
31
Django views
A view is a python code that takes a request
object returns a response object
add ppw/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse ("Hello wolrd!")
Open http://localhost:8000/ppw/!
Congrats, it works!
32
Django templates
● Most of frameworks include template
engines
● Our apps likely has a lot of html that
doesn’t change (ex: header and footer) and
some that does (ex: body)
33
Django templates
New directory and file:
ppw/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> {{ name }}</title>
</head>
<body>
<h1>Hello My Name is {{ name }}</h1>
</body>
</html>
34
Django templates
Updated ppw/views.py
from django.shortcuts import render
def index(request):
response = {'name' : mhs_name}
return render(request,'index.html',response)
35
Django Models
36
How Django Framework Works
Your Webserver Environment Request
Run
# manage.py Web Internet
Page
Merged of html
template and Value Extracted arguments
from process from Request
Request
Page
Web
index.html views.py
Person Post
display_name author
phone_number content
id_line published_date
birthday
38
Django models
Models is database tables represented in
Python code
o Creating tables
o Generating the SQL to
Create/Read/Update/Delete data
39
Django models
A model class == Database table
A model instance == a database table row
Person
display_name phone_number id_line birthday
https://docs.djangoproject.com/en/1.11/topics/db/models/
40
Django models
from django.db import models
from django.utils import timezone
from datetime import datetime, date
class Person(models.Model):
display_name = models.CharField(max_length=30)
phone_number = models.CharField(max_length=17)
id_line = models.CharField(max_length=6)
birthday = models.DateField()
class Post(models.Model):
author = models.ForeignKey(Person, on_delete =
models.CASCADE)
content = models.CharField(max_length=125)
published_date =
models.DateTimeField(default=timezone.now)
41
Django models - Fields
Important part of database is to define the
type of each attribute of a class
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.d
b.models.Field
42
Django models
Makesure your app is already installed! See
settings.py again
Run:
python manage.py makemigrations lab_1
python manage.py migrate myapp
43
Django models and views
from django.schortcuts import render
from .models import Person, Post
def index(request):
persons = Person.objects.all().values()
response = {‘name’ : mhs_name, ‘persons’ : persons}
return render(request, ‘index.html’, response)
44
Django ORM and QuerySets
python manage.py shell
Create object
>>> from lab_1.models import Person, Post
>>> from datetime import datetime, date
>>> p = Person.objects.create(
display_name=’Kak PeWe’,
phone_number = ‘+628123456’
id_line = ‘len123’
birthday = datetime.date(2017,8,28))
>>> p.save()
https://docs.djangoproject.com/en/1.11/ref/models/querysets/
45
Django models and views
index.html
46
Django ORM and QuerySets
Read object
>>> Person.objects.all()
>>> Person.objects.all().values()
47
Django admin
http://[your_url]/admin
ex: http://localhost:8000/admin
48
What & Why we use Django admin?
o Django Admin is an internal application
from Django to help developer/web admin
for day-to-day operations, browsing data &
support
o Manage your data (Create, Read, Update &
Date), integrated with your Models for
every installed applications in Django
Framework
49
How to Enable Django admin?
- CREATE SUPERUSER
python manage.py createsuperuser
50
Register Model to Django admin
- Open your app directory, find file
admin.py
- Register your model
- Open http://localhost:8000/admin/
51
Check your Model on Django Admin
52
Further Reading
https://www.djangoproject.com/
Some sources can be whatched on youtube
53