Chuyển đến nội dung chính

Bài 1: Giới thiệu Django - The Web Framework for Perfectionists

Django là gì, triết lý "batteries included". So sánh Django vs FastAPI vs Flask vs Laravel. MVT architecture, Django ecosystem. Cài đặt, tạo project và app đầu tiên.

💻 Lập trình — Bài 1 Bài 1: Giới thiệu Django - The Web Framework for Perfectionists

Django: Từ Cơ bản đến Nâng cao

Phần 1: Django Fundamentals

xdev.asia

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.

FeatureDjangoFastAPIFlaskLaravel
LanguagePythonPythonPythonPHP
TypeFull-stackAPI-onlyMicroFull-stack
ORMBuilt-inSQLAlchemySQLAlchemyEloquent
AdminBuilt-inKhôngKhôngThird-party
AsyncDjango 5.xNativeLimitedKhông
Use caseFull-stack, CMSAPI, microservicesSimple appsFull-stack

2. MVT Architecture

Request → URL Router → View → Template → Response
                         ↕
                       Model ↔ Database
ComponentVai trò
ModelData layer — ORM, database schema
ViewBusiness logic — xử lý request, trả response
TemplatePresentation — 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.