Bài 02: Django Installation và Setup

Yêu Cầu Hệ Thống

Trước khi cài đặt Django, hãy đảm bảo hệ thống của bạn đáp ứng các yêu cầu sau:

Python Version

Django 5.x yêu cầu:

  • Python 3.10+ (khuyến nghị Python 3.11 hoặc 3.12)

Kiểm tra Python version:

# Kiểm tra Python versionpython --version# hoặcpython3 --version # Output mong đợi: Python 3.10.x hoặc cao hơn

Nếu chưa có Python hoặc version cũ:

Windows:

# Download từ python.org# https://www.python.org/downloads/ # Hoặc dùng Microsoft Store# Search "Python 3.12" và install

macOS:

# Dùng Homebrew (khuyến nghị)brew install [email protected] # Hoặc download từ python.org

Linux (Ubuntu/Debian):

# Update package listsudo apt update # Install Python 3.12sudo apt install python3.12 python3.12-venv python3-pip # Verify installationpython3.12 --version

Package Manager - pip

pip (Python package installer) thường đi kèm với Python:

# Kiểm tra pippip --version# hoặcpip3 --version # Output: pip 24.0 from /path/to/pip (python 3.12)

Nếu pip chưa có:

# Windows/macOSpython -m ensurepip --upgrade # Linuxsudo apt install python3-pip

Upgrade pip lên version mới nhất:

pip install --upgrade pip

Database (Optional)

Django mặc định dùng SQLite (không cần cài thêm). Cho production, bạn có thể dùng:

  • PostgreSQL (khuyến nghị)
  • MySQL/MariaDB
  • Oracle
# PostgreSQL (recommended for production)# macOSbrew install postgresql@16 # Ubuntu/Debiansudo apt install postgresql postgresql-contrib # Windows# Download từ https://www.postgresql.org/download/windows/

Virtual Environment

Virtual environment là môi trường Python độc lập, giúp quản lý dependencies cho từng project riêng biệt.

Tại Sao Cần Virtual Environment?

Vấn đề khi không dùng venv:

# Project A cần Django 4.2pip install Django==4.2 # Project B cần Django 5.0pip install Django==5.0  # ❌ Conflict với Project A!

Giải pháp với venv:

# Project A có environment riêng với Django 4.2# Project B có environment riêng với Django 5.0# Không conflict! ✅

Tạo Virtual Environment

1. Dùng venv (Built-in Python)

# Tạo thư mục projectmkdir myprojectcd myproject # Tạo virtual environmentpython -m venv venv # Hoặc với python3python3 -m venv venv # Structure tạo ra:# myproject/#   └── venv/#       ├── bin/         (Linux/macOS)#       ├── Scripts/     (Windows)#       ├── lib/#       └── include/

Tên thư mục thường dùng:

  • venv (phổ biến nhất)
  • env
  • .venv (hidden folder)
  • virtualenv

2. Activate Virtual Environment

Linux/macOS:

# Activatesource venv/bin/activate # Prompt sẽ thay đổi(venv) user@computer:~/myproject$

Windows Command Prompt:

# Activatevenv\Scripts\activate.bat # Prompt sẽ thay đổi(venv) C:\Users\YourName\myproject>

Windows PowerShell:

# Có thể cần enable script execution trướcSet-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser # Activatevenv\Scripts\Activate.ps1 # Prompt sẽ thay đổi(venv) PS C:\Users\YourName\myproject>

3. Verify Virtual Environment

# Kiểm tra Python path (phải trỏ vào venv)which python    # Linux/macOSwhere python    # Windows # Output (Linux/macOS):# /home/user/myproject/venv/bin/python # Output (Windows):# C:\Users\YourName\myproject\venv\Scripts\python.exe # Kiểm tra pip pathwhich pip    # Linux/macOSwhere pip    # Windows

4. Deactivate Virtual Environment

# Thoát khỏi virtual environmentdeactivate # Prompt trở về bình thườnguser@computer:~/myproject$

Alternative: virtualenvwrapper

virtualenvwrapper giúp quản lý nhiều virtual environments dễ dàng:

# Install virtualenvwrapperpip install virtualenvwrapper # Configure (thêm vào ~/.bashrc hoặc ~/.zshrc)export WORKON_HOME=$HOME/.virtualenvsexport PROJECT_HOME=$HOME/projectssource /usr/local/bin/virtualenvwrapper.sh # Reload shellsource ~/.bashrc # Sử dụngmkvirtualenv myproject          # Tạo và activateworkon myproject                # Activate existingdeactivate                      # Deactivatermvirtualenv myproject          # Deletelsvirtualenv                    # List all

Alternative: Conda

Nếu bạn dùng Anaconda:

# Tạo environmentconda create -n myproject python=3.12 # Activateconda activate myproject # Deactivateconda deactivate # List environmentsconda env list # Removeconda env remove -n myproject

Cài Đặt Django

Sau khi activate virtual environment, cài Django:

Cài Django Mới Nhất

# Đảm bảo đã activate venv(venv) $ pip install django # Output:# Collecting django#   Downloading Django-5.0.x-py3-none-any.whl# ...# Successfully installed django-5.0.x sqlparse-0.x asgiref-3.x

Cài Django Version Cụ Thể

# Django 4.2 LTS (Long Term Support)pip install Django==4.2 # Django 5.0pip install Django==5.0 # Latest trong 4.x seriespip install "Django>=4.2,<5.0"

Verify Installation

# Kiểm tra Django versiondjango-admin --version# Output: 5.0.x # Hoặcpython -m django --version # Kiểm tra trong Python shellpython>>> import django>>> django.VERSION(5, 0, 0, 'final', 0)>>> django.get_version()'5.0'>>> exit()

Các Packages Đi Kèm

Django tự động cài các dependencies:

# List installed packagespip list # Output:# Package    Version# ---------- -------# asgiref    3.7.2      # ASGI server# Django     5.0.0      # Django framework# sqlparse   0.4.4      # SQL parser# pip        24.0# setuptools 69.0.0

Tạo Django Project

Dùng django-admin

# Syntaxdjango-admin startproject project_name # Example: Tạo project tên "mysite"django-admin startproject mysite # Tạo project trong thư mục hiện tạidjango-admin startproject mysite .

Sự khác biệt:

# Không có dấu chấmdjango-admin startproject mysite# Structure:# mysite/#   └── mysite/#       ├── __init__.py#       ├── settings.py#       ├── urls.py#       ├── asgi.py#       └── wsgi.py#   └── manage.py # Có dấu chấmdjango-admin startproject mysite .# Structure:# mysite/#   ├── __init__.py#   ├── settings.py#   ├── urls.py#   ├── asgi.py#   └── wsgi.py# manage.py

Project Naming Conventions

Good names:

mysiteblog_projectecommerce_platformcompany_website

Avoid:

test              # Built-in Python moduledjango            # Conflicts with Djangosite              # Too genericmy-project        # Dấu gạch ngang không được123project        # Không bắt đầu bằng số

Complete Setup Example

# 1. Tạo thư mục projectmkdir django_blogcd django_blog # 2. Tạo virtual environmentpython3 -m venv venv # 3. Activate venvsource venv/bin/activate  # Linux/macOS# venv\Scripts\activate   # Windows # 4. Upgrade pippip install --upgrade pip # 5. Cài Djangopip install django # 6. Tạo Django projectdjango-admin startproject config .# Note: Dùng "config" thay vì "mysite" để tránh confusion # 7. Verify structuretree .# hoặcls -la # Output:# .# ├── config/# │   ├── __init__.py# │   ├── settings.py# │   ├── urls.py# │   ├── asgi.py# │   └── wsgi.py# ├── manage.py# └── venv/

Cấu Trúc Django Project

File và Thư Mục

mysite/                     # Root directory (tên tùy ý)├── manage.py              # Command-line utility├── mysite/                # Python package (tên phải match project)│   ├── __init__.py       # Empty file: đánh dấu directory là Python package│   ├── settings.py       # Project settings/configuration│   ├── urls.py           # URL declarations (URL routing)│   ├── asgi.py           # Entry-point cho ASGI servers│   └── wsgi.py           # Entry-point cho WSGI servers└── venv/                  # Virtual environment (nên add vào .gitignore)

Chi Tiết Từng File

1. manage.py

Công dụng: Command-line utility để tương tác với Django project.

#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""import osimport sys def main():    """Run administrative tasks."""    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')    try:        from django.core.management import execute_from_command_line    except ImportError as exc:        raise ImportError(            "Couldn't import Django. Are you sure it's installed and "            "available on your PYTHONPATH environment variable? Did you "            "forget to activate a virtual environment?"        ) from exc    execute_from_command_line(sys.argv) if __name__ == '__main__':    main()

Sử dụng:

# Run development serverpython manage.py runserver # Create apppython manage.py startapp myapp # Database migrationspython manage.py migrate # Create superuserpython manage.py createsuperuser # Django shellpython manage.py shell

2. __init__.py

Công dụng: Đánh dấu directory là Python package.

# Thường để trống# Hoặc có thể thêm: # Import để dễ accessfrom .settings import DEBUG # Package version__version__ = '1.0.0'

3. settings.py

Công dụng: Chứa tất cả configurations của Django project.

"""Django settings for mysite project."""from pathlib import Path # Build paths inside the projectBASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-...' # SECURITY WARNING: don't run with debug turned on in production!DEBUG = True ALLOWED_HOSTS = [] # Application definitionINSTALLED_APPS = [    'django.contrib.admin',      # Admin site    'django.contrib.auth',       # Authentication    'django.contrib.contenttypes',    'django.contrib.sessions',   # Session framework    'django.contrib.messages',   # Messaging framework    'django.contrib.staticfiles', # Static files] MIDDLEWARE = [    'django.middleware.security.SecurityMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [    {        'BACKEND': 'django.template.backends.django.DjangoTemplates',        'DIRS': [],        'APP_DIRS': True,        'OPTIONS': {            'context_processors': [                'django.template.context_processors.debug',                'django.template.context_processors.request',                'django.contrib.auth.context_processors.auth',                'django.contrib.messages.context_processors.messages',            ],        },    },] WSGI_APPLICATION = 'mysite.wsgi.application' # DatabaseDATABASES = {    'default': {        'ENGINE': 'django.db.backends.sqlite3',        'NAME': BASE_DIR / 'db.sqlite3',    }} # Password validationAUTH_PASSWORD_VALIDATORS = [    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},] # InternationalizationLANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_TZ = True # Static files (CSS, JavaScript, Images)STATIC_URL = 'static/' # Default primary key field typeDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Key Settings:

  • DEBUG: Development mode (True) hoặc Production mode (False)
  • INSTALLED_APPS: List các Django apps được sử dụng
  • DATABASES: Database configuration
  • SECRET_KEY: Encryption key (phải keep secret!)

4. urls.py

Công dụng: URL routing - map URLs tới views.

"""URL configuration for mysite project."""from django.contrib import adminfrom django.urls import path urlpatterns = [    path('admin/', admin.site.urls),    # Thêm URL patterns ở đây]

Example với nhiều routes:

from django.contrib import adminfrom django.urls import path, includefrom . import views urlpatterns = [    path('admin/', admin.site.urls),    path('', views.home, name='home'),    path('about/', views.about, name='about'),    path('blog/', include('blog.urls')),  # Include app URLs]

5. asgi.py

Công dụng: ASGI (Asynchronous Server Gateway Interface) configuration.

"""ASGI config for mysite project."""import osfrom django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')application = get_asgi_application()

Khi nào dùng: Async applications, WebSockets, long-lived connections.

6. wsgi.py

Công dụng: WSGI (Web Server Gateway Interface) configuration.

"""WSGI config for mysite project."""import osfrom django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')application = get_wsgi_application()

Khi nào dùng: Production deployment với Gunicorn, uWSGI, mod_wsgi.

manage.py Commands

Essential Commands

1. runserver - Chạy Development Server

# Default: http://127.0.0.1:8000/python manage.py runserver # Custom portpython manage.py runserver 8080 # Custom host và portpython manage.py runserver 0.0.0.0:8000 # Access từ networkpython manage.py runserver 0.0.0.0:8080

Output:

Watching for file changes with StatReloaderPerforming system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them. October 28, 2025 - 10:30:00Django version 5.0, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

Important Notes:

  • ⚠️ KHÔNG dùng cho production - chỉ dùng cho development
  • 🔄 Auto-reload khi code thay đổi
  • 📊 Request logging trong terminal

2. startapp - Tạo Django App

# Tạo apppython manage.py startapp blog # Structure tạo ra:# blog/#   ├── __init__.py#   ├── admin.py#   ├── apps.py#   ├── models.py#   ├── tests.py#   └── views.py#   └── migrations/#       └── __init__.py

3. migrate - Apply Database Migrations

# Apply all migrationspython manage.py migrate # Output:# Operations to perform:#   Apply all migrations: admin, auth, contenttypes, sessions# Running migrations:#   Applying contenttypes.0001_initial... OK#   Applying auth.0001_initial... OK#   ...

4. makemigrations - Create Migrations

# Tạo migrations cho tất cả appspython manage.py makemigrations # Tạo migrations cho app cụ thểpython manage.py makemigrations blog # Output:# Migrations for 'blog':#   blog/migrations/0001_initial.py#     - Create model Post

5. createsuperuser - Tạo Admin User

python manage.py createsuperuser # Interactive prompts:# Username: admin# Email address: [email protected]# Password: ********# Password (again): ********# Superuser created successfully.

6. shell - Django Shell

# Python shell với Django contextpython manage.py shell # Output:# Python 3.12.0 (main, Oct 2023)# Type "help", "copyright" for more information.>>> from django.contrib.auth.models import User>>> User.objects.all()<QuerySet []>

Enhanced shell với IPython:

pip install ipythonpython manage.py shell# Bây giờ có syntax highlighting, auto-completion

Other Useful Commands

# Check for problemspython manage.py check # Show migrationspython manage.py showmigrations # Create empty migrationpython manage.py makemigrations --empty myapp # SQL for migrationpython manage.py sqlmigrate blog 0001 # Test runnerpython manage.py test # Collect static filespython manage.py collectstatic # Clear cachepython manage.py clear_cache # Database shellpython manage.py dbshell # Show URLspython manage.py show_urls  # Requires django-extensions

Custom Commands

Bạn có thể tạo custom management commands:

# myapp/management/commands/mycommand.pyfrom django.core.management.base import BaseCommand class Command(BaseCommand):    help = 'Description of command'        def add_arguments(self, parser):        parser.add_argument('arg1', type=str)        def handle(self, *args, **options):        self.stdout.write('Running command...')        # Command logic here        self.stdout.write(self.style.SUCCESS('Done!'))

Usage:

python manage.py mycommand value1

Development Server

Starting the Server

# Basicpython manage.py runserver # Visit: http://127.0.0.1:8000/

First Time:

October 28, 2025 - 10:30:00Django version 5.0, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

Accessing the Server

In Browser:

http://127.0.0.1:8000/http://localhost:8000/

Default Page:

🚀 The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings fileand you have not configured any URLs. Here are some links to get you started:  • Documentation  • Tutorial  • Django Community

Admin Interface:

http://127.0.0.1:8000/admin/

Auto-Reload Feature

Django development server tự động reload khi code thay đổi:

# Terminal output khi save file:[28/Oct/2025 10:35:22] "GET / HTTP/1.1" 200 16351/path/to/mysite/views.py changed, reloading.Watching for file changes with StatReloaderPerforming system checks... System check identified no issues (0 silenced).October 28, 2025 - 10:35:25Django version 5.0, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

Customizing Server

# Different portpython manage.py runserver 8080# Access: http://127.0.0.1:8080/ # All network interfaces (allow external access)python manage.py runserver 0.0.0.0:8000# Access từ máy khác: http://YOUR_IP:8000/ # No reload (for debugging)python manage.py runserver --noreload # Force color outputpython manage.py runserver --force-color

Production Considerations

⚠️ NEVER use runserver in production!

Why?

  • Không secure
  • Không scalable
  • Không stable
  • Single-threaded
  • Không có load balancing

Production servers:

  • Gunicorn
  • uWSGI
  • Daphne (cho ASGI)
  • mod_wsgi (Apache)
# Example: Gunicornpip install gunicorngunicorn mysite.wsgi:application --bind 0.0.0.0:8000

Bài Tập

Bài 1: Setup Environment

Tasks:

  1. Tạo virtual environment cho project "myblog"
  2. Cài Django 5.0
  3. Verify installation
  4. Take screenshots của mỗi bước

Expected Output:

(venv) $ python -m django --version5.0.0

Bài 2: Create Project

Tasks:

  1. Tạo Django project tên "portfolio"
  2. Khám phá structure
  3. List tất cả files được tạo ra
  4. Giải thích công dụng của mỗi file

Bonus:

  • So sánh structure khi dùng django-admin startproject portfolio vs django-admin startproject portfolio .

Bài 3: Run Development Server

Tasks:

  1. Start development server
  2. Access http://127.0.0.1:8000/
  3. Access admin panel (sẽ thấy error - OK!)
  4. Try different ports
  5. Access từ browser trên điện thoại (nếu có)

Questions:

  • Development server khác production server như thế nào?
  • Tại sao không nên dùng runserver cho production?

Bài 4: Explore Commands

Tasks:

  1. Run python manage.py help
  2. List 10 commands và giải thích công dụng
  3. Try python manage.py check
  4. Try python manage.py showmigrations

Bài 5: Customize Settings

Tasks:

  1. Thay đổi LANGUAGE_CODE thành 'vi' (Vietnamese)
  2. Thay đổi TIME_ZONE thành 'Asia/Ho_Chi_Minh'
  3. Restart server và verify changes
  4. Add comment giải thích mỗi setting

Example:

# settings.pyLANGUAGE_CODE = 'vi'  # Vietnamese languageTIME_ZONE = 'Asia/Ho_Chi_Minh'  # Vietnam timezone

Challenge: Multiple Projects

Task:
Tạo 2 Django projects với 2 virtual environments riêng biệt, mỗi project dùng Django version khác nhau (4.2 và 5.0).

Requirements:

projects/├── project_v4/│   ├── venv/│   └── mysite/ (Django 4.2)└── project_v5/    ├── venv/    └── mysite/ (Django 5.0)

Troubleshooting

Common Issues

1. "django-admin not found"

# Solution: Django chưa được cài hoặc venv chưa activatepip install django# Hoặcsource venv/bin/activate

2. "Port already in use"

# Error: Error: That port is already in use. # Solution: Dùng port khácpython manage.py runserver 8080 # Hoặc kill process đang dùng port 8000# Linux/macOS:lsof -ti:8000 | xargs kill -9 # Windows:netstat -ano | findstr :8000taskkill /PID <PID> /F

3. "Python not found"

# Try different commands:python --versionpython3 --versionpy --version  # Windows # Set alias (Linux/macOS)alias python=python3

4. "Permission denied"

# Linux/macOSchmod +x manage.pypython manage.py runserver # Hoặcpython3 manage.py runserver

Tips & Best Practices

1. Always use Virtual Environment

# ✅ Goodsource venv/bin/activatepip install django # ❌ Badpip install django  # Global installation

2. Keep requirements.txt Updated

# Save dependenciespip freeze > requirements.txt # Install from requirementspip install -r requirements.txt

3. .gitignore Setup

# Python__pycache__/*.py[cod]*$py.class*.so # Django*.logdb.sqlite3/media/static # Virtual Environmentvenv/env/ENV/ # IDE.vscode/.idea/*.swp*.swo # OS.DS_StoreThumbs.db

4. Environment Variables

# Create .env fileSECRET_KEY=your-secret-key-hereDEBUG=TrueDATABASE_URL=postgresql://user:pass@localhost/dbname # Install python-decouplepip install python-decouple # Use in settings.pyfrom decouple import config SECRET_KEY = config('SECRET_KEY')DEBUG = config('DEBUG', default=False, cast=bool)

Tài Liệu Tham Khảo

Official Documentation

Video Tutorials

  • Django Setup for Beginners - Corey Schafer
  • Django Installation - Tech With Tim
  • Python Virtual Environments - Real Python

Tools

Next Steps


Previous: Bài 01: Giới Thiệu Django | Next: Bài 03: Django Apps