0% found this document useful (0 votes)
24 views

03 - MTV Django Architecture

Uploaded by

Fransisca Ellya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

03 - MTV Django Architecture

Uploaded by

Fransisca Ellya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

MTV Django Architecture

Tim Dosen PBP


Additional Materials
Forms of Cloud Computing
Software as a Service (SaaS)
Ready-to-use application software running on Cloud
infrastructures. Examples: Gmail, Microsoft Office 365, and
Dropbox.

Platform as a Service (PaaS)


It offers full or partial application development software and
libraries for developers such as Google App Engine and AWS
Elastic Beanstalk which are callable over the internet.

Infrastructure as a Service (IaaS)


It delivers raw computer infrastructure in the form of virtual
machines which can be scaled up and down based on application
resource needs. Examples: Amazon Elastic Compute Cloud
(Amazon EC2), Google Compute Engine (GCE), and IBM Cloud.

3
CI/CD
• Continuous integration (CI) automatically builds, tests, and integrates code changes
within a shared repository

• Continuous delivery (CD) automatically delivers code changes to production-ready


environments for approval

• Continuous deployment (CD) automatically deploys code changes to customers directly

4
MTV Django Architecture
Django MTV Architecture

Django is often referred to as an MTV


framework
● M stands for “Model”: the data access
layer
● T stands for “Template”: the
presentation layer : html
● V stands for “View”: the business
logic layer, the bridge between models
and templates. akan menghasilkan http response, html

6
Question
Separation of Concern: Why we need it? What are the benefits of it?
Separation of concern : membagi tugas pada code sehingga kode bisa lebih modular.

MTV dibutuhkan karena

Manfaat

7
How Django Framework Works Laptop : user dan mengirim request
-r : read
Kenapa kita harus membuat virtual environment?
Agar tidak terjadi conflict antara package.

Your Webserver Environment Request

Run Web Internet


# manage.py Page
Merged of html template
and Value from process Extracted arguments
from Request

Page
Web

Request
index.html views.py
It’s your html It’s your python
template code code

models.py Access to URL (on Browser):


DB It’s your model
code https://[appname].pbp.cs.ui.ac.id/
8

8
Installing Django
Installing Django
1. Install Python MY LAPTOP
“Being a Python web framework, Django requires Python”
2. Install and activate a Python Virtual Environment
C:\Project\ C:\Project\PBP\
Lomba\ MyWeb\
python -m venv env Eg: Django 1.7 Eg: Django 3.2
env\Scripts\activate.bat

3. Install Django and/or required dependencies PC LAB


D:\Data\PBP\
pip install django MyWeb
Eg: Django 4.1.1
Or
Server di Luar Negeri
pip install -r requirements.txt
/home/pbp/
Eg: Django 3.2

10
Django Project vs Django App
MVC tidak memiliki project
Djangoo bisa membuat app

1 modul django bisa menggunakan lebih dari 1 app.


Question
What is the difference between Django project and Django app?
Django Project memiliki collections, database

12
Django Project vs Django App
• Django Project
• A Django project – a collection of settings for an instance of Django, including
database configuration, Django-specific options and application-specific settings.
• A project is a collection of configuration and apps for a particular website.
• A project can contain multiple apps.
• Django App
• An app is a web application that does something – e.g., a blog system, a database
of public records or a small poll app.
• An app can be in multiple projects.

13

13
Urls.py dapat mngakses urls.py app.
untuk menjalankannya menggunakan setings.py
Django Project
• Start a project
django-admin startproject contohproject

• Auto-generated files:
contohproject/
contohproject/
__init__.py
asgi.py
settings.py (configuration for the project)
urls.py (starting point to configure urls)
wsgi.py
manage.py (command runner)

• For other django-admin commands, see Django documentation. 15

15
Django Development Server
• Start up a development server

cd contohproject
python manage.py runserver

• The Django development server is meant to be used only during development so you can
develop things rapidly, without having to deal with configuring a production server – such as
Apache – until you’re ready for production.
• By default, the runserver command starts the development server on the internal IP at port
8000.
• After the server’s running, visit http://127.0.0.1:8000/ or http://localhost:8000/ with your
web browser.

16

16
Django App
• Build an app

django-admin startapp contohapp

• The directory structure of the newly created contohapp application:

contohapp/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py 17

17
Django App
• We have to tell Django that it should use the contohapp application.
• Open contohproject/settings.py and add contohapp in the INSTALLED_APPS
setting,

INSTALLED_APPS = [ Baca di Django documentation, apa


'django.contrib.admin', saja aplikasi yang secara default
'django.contrib.auth', sudah ada di INSTALLED_APPS
setting dan apa fungsi dari masing-
'django.contrib.contenttypes',
masing aplikasi tersebut.
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'contohapp',
]

18
Django URLs and Views
Django URLs and Views

Inside Your “Webserver” Request

Listen at some
host and
Web Internet
port(s) Page

Parsed

Request
Request

Page
Web
URL routing

ex: /contact ex: /projects


ex: /login

Your Code1 Your Code2 Your Code3


Access to URL (on Browser):
https://[appname].pbp.cs.ui.ac.id/
20
Django URLs
• Django URLs forward request to appropriate view
• Django maps arguments from request or url to a view by using regular expression

• Contoh: supaya dapat mengakses contohapp di http://localhost:8000/contohapp


1. Buatlah berkas urls.py di direktori aplikasi contohapp
2. Tulis di dalam berkas tersebut:

from django.urls import include, path


from .views import index

urlpatterns = [
path('', index, name='index'),
]

21
Django URLs
3. Di dalam berkas urls.py yang ada direktori project contohproject, import
django.urls.include dan tambahkan modul contohapp.urls di dalam variabel
urlpatterns sehingga isi berkas urls.py menjadi:

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('contohapp', include('contohapp.urls')),
]

include untuk import

22
Django Views
• A view function, or view for short, is a Python function that takes a web request and returns
a web response. This response can be the HTML contents of a web page, a redirect, a 404
error, an XML document, an image, or anything.

• Untuk contohapp, setelah membuat konfigurasi urls, selanjutnya adalah buka berkas
views.py yang ada di direktori contohapp dan tambahkan kode berikut ini:

from django.http import HttpResponse

def index(request):
return HttpResponse ("Hello world!")

• Sekarang seharusnya http://localhost:8000/contohapp sudah dapat diakses di web browser.

23
Django Views and Templates
Django Views and Templates

Request
Your App1
urls.py
Templates Folder URL routing Web Internet
Page
Merged of html template Extracted arguments
and Value from process from Request

views.py

Request
Page
Web
index.html
It’s your html
template code
It’s your python
code

Access to URL (on Browser):


https://[appname].pbp.cs.ui.ac.id/
25

25
Django Templates
• Most of frameworks include template engines Untuk contohapp, buatlah folder bernama “templates” di
• Our apps likely has a lot of html that doesn’t dalam direktori aplikasi contohapp dan di dalam folder
change (ex: header and footer) and some that tersebut, buatlah berkas index.html berisi kode berikut ini:
does (ex: body)
• By convention DjangoTemplates looks for a <!DOCTYPE html>
“templates” subdirectory in each of the
<html lang="en">
INSTALLED_APPS.
<head>
• Subdirektori “templates” harus kita buat <meta charset="UTF-8">
sendiri. <title>{{ name }}</title>
</head>
<body>
<h1>Hello My Name is {{ name }}</h1>
</body>
</html>

26
Django Views and Templates

Views Templates

Update contohapp/views.py menjadi: <!DOCTYPE html>


<html lang="en">
from django.shortcuts import render <head>
<meta charset="UTF-8">
<title>{{ name }}</title>
mhs_name = 'Mahasiswa PBP'
</head>
<body>
def index(request): <h1>Hello My Name is {{ name }}</h1>
response = {'name' : mhs_name} </body>
return render(request,'index.html',response) </html>

Fungsi render untuk mengeload gambar per page

Coba cek http://localhost:8000/contohapp di browser


27
Django Views and Models
views : menghubungkan urls, template, dan model
Django Views and Models

Request
Your App1
urls.py
Templates Folder URL routing Web Internet
Page
Merged of html template Extracted arguments
and Value from process from Request

views.py

Request
Page
Web
index.html
It’s your python
It’s your html
code
template code

DB models.py
Access to URL (on Browser):
https://[appname].pbp.cs.ui.ac.id/
29

29
Django Models
• Models are a set of data stored to be processed in our apps. We store them in form of tables that connect
to one another. We can create, read, update, and delete (CRUD) data from the tables using several
specific command instructions called SQL.
Post
• Do you know or remember what is object?
Object : instance of class Person author

display_name content

phone_number published_date

• A model class == a database table Person


• A model instance == a database table row display_name phone_number

Kak PeBePe +628123456

Budi +6281676732

30
Create Django Models
Update contohapp/models.py:

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)

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)
ForeignKey : suatu jenis field yang membuat relasi dari antara dua model atau beberapa contoh dari post ke person.

31
Django Models - Field
Important part of database is to define the type of each attribute of a class
● models.CharField - define text with limited number of chars
● models.DateField - a date only
● models.DateTimeField - a date and time
● models.ForeignKey - a link to another model
● etc ..

32
Django Models
• Make sure your app is already installed! See settings.py again
• Run:
python manage.py makemigrations Kenapa makemigrations dan
migrate dipisah menjadi dua
python manage.py migrate
commands?
Apa yang terjadi jika kita hanya
menjalankan makemigrations
• The three-step guide to making model changes: tanpa migrate?
1. Change your models (in models.py)
2. Run python manage.py makemigrations to create migrations for those
changes
untuk mempersiapkan migrasi skema model ke dalam database Django lokal
3. Run python manage.py migrate to apply those changes to the database
untuk menerapkan skema model yang telah dibuat ke dalam database Django lokal

33
Django Admin
Django Admin
• Django Admin is an internal application from Django to help
developer/web admin for day-to-day operations, browsing data & support
• By default, the admin site url is http://localhost:8000/admin/
• To create a user to login with, use the createsuperuser command

python manage.py createsuperuser

(input username, email, and password)

35
Django Admin - Register
• To register models to Django Admin, update contohapp/admin.py:

from django.contrib import admin


from .models import Person, Post

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

• Open http://localhost:8000/admin/
• Add some Person objects in Django Admin

36
Django Models and Views
• Update contohapp/views.py:

from django.shortcuts import render


from .models import Person, Post

mhs_name = 'Kak PeBePe'

def index(request):
persons = Person.objects.all().values()

response = {'name' : mhs_name, 'persons' : persons}


return render(request, 'index.html', response)

37
Django Models and Templates
• Update contohapp/templates/index.html:

...
<body>
{% if persons %}
{% for person in persons %}
{{ person.display_name }}
<br/>
{% endfor %}
{% endif %}
</body>
...

Coba cek http://localhost:8000/contohapp di browser


38
Django Tests
Django Tests
• Automated testing is an extremely useful bug-killing tool for the modern Web
developer. You can use a collection of tests – a test suite – to solve, or avoid, a
number of problems:

• When you’re writing new code, you can use tests to validate your code works as
expected.
• When you’re refactoring or modifying old code, you can use tests to ensure your
changes haven’t affected your application’s behavior unexpectedly.

• The default startapp template creates a tests.py file in the new application.

40
Django Tests Sample
• Update contohapp/tests.py:

from django.test import TestCase, Client


from django.urls import resolve
from .views import index

class ContohAppTest(TestCase):
def test_contoh_app_url_is_exist(self):
response = Client().get('/contohapp')
self.assertEqual(response.status_code,200)

def test_contoh_app_using_person_list_template(self):
response = Client().get('/contohapp')
self.assertTemplateUsed(response, 'index.html')
41
Django Tests & Code Coverage
Code coverage : sebuah code yang bisa memberikan deskripsi tentang sudah ditest belum codenya.
dan di compare yang udah dan belum ditesting
• Run test: python manage.py test
• Code coverage
• Code coverage describes how much source code has been tested. It shows which parts
of your code are being exercised by tests and which are not. It’s an important part of
testing applications, so it’s strongly recommended to check the coverage of your tests .
• To install coverage package: pip install coverage
• To run tests and collect coverage data of the executed files in the project:
coverage run --source='.' manage.py test

• To see a report of coverage data:


coverage report --show-missing

• Note: Code coverage can only indicate that you’ve forgotten tests; it will not tell you
whether your tests are good. Don’t use good code coverage as an excuse to write lower
quality tests.
42
Code Coverage

Code coverage means what percentage of your codebase is covered by the tests or being
tested. If you have no tests, then the code coverage is zero.
(https://codeburst.io/10-reasons-why-code-coverage-matters-9a6272f224ae)

43
Additional Materials
Test-Driven Development (TDD)
• TDD is “rediscovered” by Kent Beck.
• TDD is related to the test-first programming concepts of
Extreme Programming (one of Agile Software Development
methods).
TDD : compare hasil manual dan expected output

45
TDD – Unit Tests and Functional Tests
• One of the values and principles of Extreme Programming:
Feedback
❑ Feedback from the system: unit tests

❑ Feedback from the customer: functional tests

❑ Feedback from the team: When customers come up with

new requirements, the team directly gives an estimation of


the time that it will take to implement.

46
TDD Remarks
• Compare actual result with expected result
• TDD: Think expected result first, write on the test. Later,
define the real function that gives the actual result
• Tests are developed FIRST before the code
• Modern TDD: automated testing

47
TDD Cycle
• Red – write a failing test
• Green – make the smallest change to pass the test
• Refactor – refactor to improve the code, e.g. remove
duplicate code

48
TDD Cycle

49
Double-loop TDD
(The TDD process
with functional
and unit tests)

50
Unit Test vs Functional Test
Unit Test Functional Test
• Test the smallest unit (function, class, • User Acceptance tests, or end-to-end
model, etc.) tests end to end tests : menguji dari ujung ke ujung (dari ujung
awal pengembangan aplikasi dan realease ke user)
• Black box – test from the outside • Look at how the whole application
• White box – test from the inside functions, from the outside
• Should have a human-readable input- • Black box test, because the test doesn’t
output comparison know anything about the internals of
• Make it explicit using comments that the system under test
accompany the implementation code. • Should have a human-readable story
(Code documentation) that we can follow
• Make it explicit using comments that
accompany the test code

51
Unit Test
• Unit testing is a software development process in which the
smallest testable parts of an application, called units, are
individually scrutinized for proper operation.
• The main objective of unit testing is to isolate written code to
test and determine if it works as intended.
• Developers can perform unit tests manually or automatically.

52
Unit Testing in Django
• Django provides a mechanism to create unit test –
augmented version from standard unit test in python
• The default startapp template creates a tests.py file in the
new application.

53
Hierarchy of Django Unit Testing Class
• Normal Python unit
test classes extend a
base class of
unittest.TestCase
• Django provides a few
extensions of this
base class
• All of the standard
Python unit test
functionality will be
available and it will be
augmented with some
useful additions

54
Assert Methods in Python is (assertIs)-> buat ngecek alamat
= (assertEqual) -> mengecek value

55
Assert Methods in Django
• As Python’s normal unittest.TestCase class implements
assertion methods such as assertTrue() and
assertEqual(), Django’s custom TestCase class
provides a number of custom assertion methods that are
useful for testing web applications, e.g assertContains,
assertNotContains, and assertTemplateUsed.
• For other Django assert methods, see Django
documentation.

56
Apa yang perlu dites di Django?
1. URL
• Bayangkan URL seperti apa yang diharapkan.
• Rancang juga FUNGSI apa yang akan dipanggil oleh
URL tersebut.
• Buat test-nya terlebih dahulu.

57
Apa yang perlu dites di Django?
2. MODELS
• Bayangkan nama models yang akan dibuat, misalnya
Person (atribut: nama dan alamat)
• Buat satu object untuk model tersebut di tests.py
Person.objects.create(nama=’Bepe’,alamat=‘JKT’)
• Cek apakah data berhasil dimasukkan ke database
• Hitung jumlah object
hitungjumlah = Person.objects.all().count()
self.assertEqual(hitungjumlah,1)

58
Apa yang perlu dites di Django?
3. FUNGSI - VIEWS.py
• Setiap baris fungsi pada views.py harus dites
• Periksa setiap kemungkinan, buat test untuk setiap case
yang ada, misalnya jika ada if else, buatlah test untuk
if dan buat juga test untuk else
• Baca di dokumentasi Django, method Assert apa yang
cocok untuk fungsi yang dibuat

59
Apa yang perlu dites di Django?
4. HTML terkait
• Cek apakah file HTML digunakan
self.assertTemplateUsed
• Cek apakah ada konten tertentu di HTML
self.assertIn

60
Functional Testing in Django
• Django also provides special support for in-browser
frameworks like Selenium. For more details, see Django
documentation
• To install: run pip install selenium or add selenium to
your requirements.txt

61
References
- Django documentation. Accessed: July 14, 2024. [Online]. Available:
https://docs.djangoproject.com/en/5.0/
- R. Hamedy. "10 Reasons Why Code Coverage Matters". codeburst.io. Accessed: Jul. 14, 2024.
[Online]. Available: https://codeburst.io/10-reasons-why-code-coverage-matters-
9a6272f224ae
- TechTarget Contributor. "unit testing". TechTarget. Accessed: July 31, 2024. [Online].
Available: https://www.techtarget.com/searchsoftwarequality/definition/unit-testing

62

You might also like