03 - MTV Django Architecture
03 - MTV Django Architecture
3
CI/CD
• Continuous integration (CI) automatically builds, tests, and integrates code changes
within a shared repository
4
MTV Django Architecture
Django MTV Architecture
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.
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.
Page
Web
Request
index.html views.py
It’s your html It’s your python
template code code
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
10
Django Project vs Django App
MVC tidak memiliki project
Djangoo bisa membuat app
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)
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
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,
18
Django URLs and Views
Django URLs and Views
Listen at some
host and
Web Internet
port(s) Page
Parsed
Request
Request
Page
Web
URL routing
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:
urlpatterns = [
path('admin/', admin.site.urls),
path('contohapp', include('contohapp.urls')),
]
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:
def index(request):
return HttpResponse ("Hello world!")
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
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
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
Budi +6281676732
30
Create Django Models
Update contohapp/models.py:
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
35
Django Admin - Register
• To register models to Django Admin, update contohapp/admin.py:
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:
def index(request):
persons = Person.objects.all().values()
37
Django Models and Templates
• Update contohapp/templates/index.html:
...
<body>
{% if persons %}
{% for person in persons %}
{{ person.display_name }}
<br/>
{% endfor %}
{% endif %}
</body>
...
• 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:
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
• 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
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