Django
Django
Nội dung
• Tổng quan Django framework
• Cấu trúc project Django
• MVT Pattern (Model-View-Template)
• Lập trình Web với Django
• Ref: The web framework for perfectionists with deadlines | Django (djangoproject.com)
2
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Tổng quan
• Django là web framework miễn phí, mã nguồn mở để xây dựng các ứng dụng web Python hiện đại
• Django giúp nhanh chóng xây dựng các ứng dụng web bằng cách xây dựng sẵn các thành phần và tái
sử dụng như kết nối với cơ sở dữ liệu, xử lý bảo mật, cho phép xác thực người dùng, tạo URL, hiện thị
nội dung thông qua các templates và forms, hỗ trợ nhiều CSDL backends, và thiết lập giao diện hiển thị
• Developers chỉ cần tập trung vào xây dựng chức năng của ứng dụng web thay vì phải làm lại các chức
năng chuẩn của 1 ứng dụng web
• Django được sử dụng phổ biến
3
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Cấu trúc dự án
• manage.py
- Không nên sửa đổi
- File giúp thực hiện các thao tác quản trị, vd như chạy máy
chủ cục bộ
Cấu trúc thư mục dự án sau khi
(myenv) $ python3 manage.py runserver tạo và chạy máy chủ cục bộ
• db.sqlite3 bằng lệnh runserver
- Chứa CSDL
• testProject
5
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
6
Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default browser to that address.
8
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
9
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
urlpatterns = [
path("", include("hello.urls")),
path('admin/', admin.site.urls)
• ]
10
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
11
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
12
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
15
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
- In the static/hello folder, create a file named site.css with the following contents:
.message {
font-weight: 600;
color: blue;
}
16
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• Also in templates/hello/hello_there.html, replace the contents <body> element with the following
markup that uses the message style instead of a <strong> tag:
<span class="message">Hello, there {{ name }}!</span> It's {{ date | date:'l, d
F, Y' }} at {{ date | time:'H:i:s' }}.
17
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
19
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact
pages, which you create in a later section
• Notice the use of Django's {% url %} tag to refer to other pages through the names of the corresponding
URL patterns rather than by relative path.
20
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
<body>
<div class="navbar">
<a href="{% url 'home' %}" class="navbar-brand">Home</a>
<a href="{% url 'about' %}" class="navbar-item">About</a>
<a href="{% url 'contact' %}" class="navbar-item">Contact</a>
</div>
<div class="body-content">
{% block content %}
{% endblock %}
<hr/>
<footer>
<p>© 2024</p>
</footer>
</div>
</body>
</html>
21
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
22
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
.navbar a {
text-decoration: none;
color: inherit;
}
.navbar-brand {
font-size: 1.2em;
font-weight: 600;
}
.navbar-item {
font-variant: small-caps;
margin-left: 30px;
}
.body-content {
padding: 5px;
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
} 23
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
24
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
"$0",
"{% endblock %}",
"{% block content %}",
"{% endblock %}"
],
},
25
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
- At the insertion point in the "title" block, write Home, and in the "content" block, write <p>Home page
for the Visual Studio Code Django tutorial.</p>, then save the file. These lines are
the only unique parts of the extended page template:
- In the templates/hello folder, create about.html, use the snippet to insert the boilerplate
markup, insert About us and <p>About page for the Visual Studio Code Django
tutorial.</p> in the "title" and "content" blocks, respectively, then save the file.
26
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
27
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• It's fine to add or delete records in tables using such a tool, but avoid
making changes to the database schema because the database will
then be out of sync with your app's models
Define models
• A Django model is again a Python class derived from django.db.model.Models, which you place in the
app's models.py file
• All other fields are defined as properties of the class using types from django.db.models such as
CharField (limited text), TextField (unlimited text), EmailField, URLField, IntegerField,
DecimalField, BooleanField. DateTimeField, ForeignKey, and ManyToMany, among others.
• Each field takes some attributes, like max_length. The blank=True attribute means the field is optional;
null=true means that a value is optional. There is also a choices attribute that limits values to values in
an array of data value/display value tuples.
30
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Define models
• For example, add the following class in models.py to define a data model that represents dated entries in a
simple message log:
from django.db import models
from django.utils import timezone
class LogMessage(models.Model):
message = models.CharField(max_length=300)
log_date = models.DateTimeField("date logged")
def __str__(self):
"""Returns a string representation of a message."""
date = timezone.localtime(self.log_date)
return f"'{self.message}' logged on {date.strftime('%A, %d %B, %Y at
%X')}" 31
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• In VS Code, open a Terminal with your virtual environment activated (use the Terminal: Create New
Terminal command, Ctrl+Shift+`)), navigate to the project folder, and run the following commands:
- python manage.py makemigrations
- python manage.py migrate
Take a look in the migrations folder to see the scripts that makemigrations generates. You can also look at the
database itself to see that the schema is updated.
32
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
33
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• Note: Django's {% csrf_token %} tag provides protection from cross-site request forgeries. See Cross
Site Request Forgery protection in the Django documentation for details. 34
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
35
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
38
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
{% if message_list %}
<table class="message_list">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Message</th>
</tr>
</thead>
<tbody>
{% for message in message_list %}
<tr>
<td>{{ message.log_date | date:'d M Y' }}</td>
<td>{{ message.log_date | time:'H:i:s' }}</td>
<td>
{{ message.message }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No messages have been logged. Use the <a href="{% url 'log' %}">Log Message form</a>.</p>
{% endif %}
{% endblock %}
39
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
40
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
41
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
class HomeListView(ListView):
"""Renders the home page, with a list of all messages."""
model = LogMessage
42
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
43
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
44
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Anyone (or any build server) that receives a copy of the project needs only to run the pip install -r
requirements.txt command to reinstall the packages on which the app depends within the active
environment.
45
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
5. Once you're authenticated, you see the default administration page, through which you can manage users and groups:
47
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Cấu trúc dự án
• __pycache__: Thư mục lưu trữ bytecode được biên dịch khi tạo dự án,
mục đích làm dự án bắt đầu nhanh ơn bằng cách lưu code đã biên dịch
vào bộ nhớ cache để sau đó nó có thể dễ dàng thực thi
• __init__.py: File chỉ định những gì sẽ chạy khi Django khởi chạy lần đầu
• asgi.py: File cho phép tùy chọn Asynchronous Server Gateway Interface
(Giao diện cổng máy chủ không đồng bộ) chạy
• settings.py: File quan trọng chứa cài đặt của dự án
• urls.py: File cho Django biết trang nào sẽ hiển thị theo yêu cầu của trình
duyẹt hoặc URL.
• wsgi.py: (Web Server Gateway Interface – Giao diện cổng máy chủ web)
giúp Django phục vụ trang web
48
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
50
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
• Mặc dù app mới tạo tồn tại trong dự án của Django nhưng phải
thêm vào settings.py thì Django mới nhận ra
... settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testapp'
]
...
51
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
URLs
• urls.py
from django.contrib import admin urls.py
from django.urls import path
from testapp import views as testviews
urlpatterns = [
path('admin/', admin.site.urls),
path('', testviews.home),
path('about/', testviews.about)
]
Ref: django.urls functions for use in URLconfs | Django documentation | Django (djangoproject.com)
52
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
URLs
• urls.py
from django.contrib import admin urls.py
from django.urls import path
from testapp import views as testviews
urlpatterns = [
path('admin/', admin.site.urls),
path('', testviews.home),
from django.shortcuts import render views.py
path('about/', testviews.about)
from django.http import HttpResponse
]
def home(request):
return HttpResponse('<h1>Welcome to Home Page</h1>')
def about(request):
return HttpResponse('<h1>Welcome to About Page</h1>')
Ref: django.urls functions for use in URLconfs | Django documentation | Django (djangoproject.com)
53
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
def home(request):
return render(request, 'home.html')
54
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
... home.html
<body>
<h1>Welcome to Home Page, {{ name }}</h1>
<h2>This is the full home page</h2>
</body>
...
Models
from django.db import models
class Movie(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=250)
image = models.ImageField(upload_to='movie/images/')
url = models.URLField(blank=True)
• Module models giúp xác định và ánh xa các trường của mô hình vào CSDL
• Lớp Movie kế thừa từ lớp Model. Lớp Model cho phép tương tác với CSDL, tạo bảng, truy xuất và
thực hiện các thay đổi đối với dữ liệu trong CSDL
• Ref: Model field reference | Django documentation | Django (djangoproject.com)
56
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Migrations
• Migrations cho phép tạo 1 lược đồ CSDL dựa trên code model
• Mỗi khi model thay đổi (thêm trường, đổi tên trường), migration
sẽ được tạo ra theo dõi quá trình phất triển của lược đồ
CSDL (dưới dạng hệ thống kiểm soát phiên bản)
57
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
58
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Mô hình MVT
59
Khoa CÔNG NGHỆ THÔNG TIN
Nguyễn Thị Lệ Quyên
Mô hình MVC
60