0% found this document useful (0 votes)
100 views53 pages

Intro To Framework, Server Side Programming With Django

This document provides an introduction to the Django web framework and server-side programming. It discusses how Django provides basic building blocks and code reusability through its model-view-controller pattern. It also covers installing and setting up a Django project and applications, Django's URL routing system, and creating views and templates to build out the frontend. The key aspects of Django that it aims to introduce are its rapid development capabilities, separation of concerns, and focus on building applications rather than dealing with lower-level web details.

Uploaded by

Oktafia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views53 pages

Intro To Framework, Server Side Programming With Django

This document provides an introduction to the Django web framework and server-side programming. It discusses how Django provides basic building blocks and code reusability through its model-view-controller pattern. It also covers installing and setting up a Django project and applications, Django's URL routing system, and creating views and templates to build out the frontend. The key aspects of Django that it aims to introduce are its rapid development capabilities, separation of concerns, and focus on building applications rather than dealing with lower-level web details.

Uploaded by

Oktafia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

04.

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

Get Stuff Done!

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

Since then, wide communities, web


programmers contributes and makes sure
Django saves their time.

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

o Model: contains functions to retrieve,


insert, update, delete from or to database
o View: the presentation layer to the user,
what you see on the browser
o Controller: intermediary tier between
model and view

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

Your Code1 Your Code1 Your Code1


Access to URL (on Browser):
http://[appname].herokuapp.com/

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

It’s your html It’s your python


template code code

Value from process view.py Access to URL (on Browser):


http://[appname].herokuapp.com/

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

See the folder:


draft_lab/
draft_lab/manage.py
draft_lab/draft_lab
draft_lab/draft_lab/settings.py
draft_lab/draft_lab/urls.py
draft_lab/draft_lab/wsgi.py
draft_lab/draft_lab/_init_.py

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

Listen at some host and Web


port(s) Internet
manage.py (runner) Page
setting.py (parameter)

Parsed Request

Request
URL routing: urls.py

Page
Web
ex: /search
ex: /
ex: /login

search.py view2.py view.py


Access to URL (on Browser):
http://[appname].herokuapp.com/

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.

Create your own app in sub directory of your


project:
python manage.py startapp [app_label]

25
Applications
$ python manage.py startapp ppw

See the folder:


ppw/admin.py
ppw/apps.py
ppw/migrations
ppw/migrations/_init_.py
ppw/models.py
ppw/tests.py
ppw/views.py
ppw/_init_.py

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

from django.conf.urls import url, include


from django.contrib import admin

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

from django.conf.urls import url


from .views import index

urlpatterns = [
url(r'^$', index, name='index'),
]

30
Django urls 2.1
draft_lab/urls.py

from django.urls import include, path


from django.contrib import admin

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

mhs_name = ‘Mahasiswa Fasilkom'

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

It’s your html It’s your python


template code code

models.py Access to URL (on Browser):


DB http://[appname].herokuapp.com/
It’s your model
code
37
Objects - A Review
Imagine Line social media

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

Kak PeWe +628123456 len123 28-08-2017

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

o models.CharField - define text with limited


number of chars
o models.DateField - a date only
o models.DateTimeField - a date and time
o models.ForeignKey - a link to another model
o etc ..

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

mhs_name = ‘Kak Pewe’

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()

<QuerySet [<Person: Person object>]>

>>> Person.objects.all().values()

<QuerySet [{'id': 1, 'display_name': 'Kak PeWe',


'phone_number': '+628123456', 'id_line': 'len123',
'birthday': datetime.date(2017, 8, 28)}]>

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

Input username, email, and password

50
Register Model to Django admin
- Open your app directory, find file
admin.py
- Register your model

from .models import Person, Post


admin.site.register(Person)
admin.site.register(Post)

- 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

You might also like