1. Django là gì?
Django là Python web framework "batteries included" — cung cấp sẵn ORM, admin panel, authentication, form processing, template engine và nhiều module khác ngay từ đầu.
| Feature | Django | FastAPI | Flask | Laravel |
|---|---|---|---|---|
| Language | Python | Python | Python | PHP |
| Type | Full-stack | API-only | Micro | Full-stack |
| ORM | Built-in | SQLAlchemy | SQLAlchemy | Eloquent |
| Admin | Built-in | Không | Không | Third-party |
| Async | Django 5.x | Native | Limited | Không |
| Use case | Full-stack, CMS | API, microservices | Simple apps | Full-stack |
2. MVT Architecture
Request → URL Router → View → Template → Response
↕
Model ↔ Database
| Component | Vai trò |
|---|---|
| Model | Data layer — ORM, database schema |
| View | Business logic — xử lý request, trả response |
| Template | Presentation — HTML rendering |
3. Cài đặt & Tạo Project
# Python virtual environment
python -m venv .venv
source .venv/bin/activate
# Cài Django
pip install django djangorestframework
# Tạo project
django-admin startproject config .
# Tạo app
python manage.py startapp users
python manage.py startapp products
4. Cấu trúc Project
myproject/
├── config/
│ ├── __init__.py
│ ├── settings.py # Configuration
│ ├── urls.py # Root URL routing
│ ├── wsgi.py # WSGI entry
│ └── asgi.py # ASGI entry (async)
├── users/
│ ├── models.py # Data models
│ ├── views.py # View logic
│ ├── urls.py # App URL routing
│ ├── serializers.py # DRF serializers
│ ├── admin.py # Admin config
│ └── tests.py # Tests
├── manage.py
└── requirements.txt
5. Settings cơ bản
# config/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'rest_framework',
# Custom apps
'users',
'products',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'postgres',
'PASSWORD': 'secret',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Chạy migrations & server
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Bài tiếp theo: Models & Django ORM — fields, relationships, managers.