Danh sách bài viết

Django Basic - Cơ Bản Django

Khóa học Django Basic giúp bạn nắm vững các khái niệm cơ bản của Django framework để xây dựng web applications hoàn chỉnh.

14/05/2026
10 phút đọc
1 lượt xem

Mục Tiêu Module

Học các khái niệm cơ bản của Django framework để xây dựng web applications.

Danh Sách Bài Học

1. Giới Thiệu Django

  • Django là gì?
  • MVT (Model-View-Template) pattern
  • Django vs Flask vs FastAPI
  • Khi nào nên dùng Django
  • Django ecosystem

2. Django Installation và Setup

  • Cài đặt Django
  • Tạo project với django-admin
  • Cấu trúc Django project
  • manage.py commands
  • Development server

3. Django Apps

  • Apps là gì?
  • Tạo app với startapp
  • Đăng ký apps trong INSTALLED_APPS
  • App structure
  • Reusable apps

4. URLs và Views

  • URL routing
  • URLconf (urls.py)
  • path() và re_path()
  • URL parameters
  • Function-based views
  • HttpRequest và HttpResponse

5. Templates

  • Template engine
  • Template syntax ({{ }}, {% %})
  • Template variables
  • Template filters
  • Template tags
  • Template inheritance (extends, block)
  • include templates

6. Static Files

  • STATIC_URL và STATIC_ROOT
  • Organizing static files (CSS, JS, images)
  • {% load static %}
  • {% static %} tag
  • collectstatic command

7. Models Cơ Bản

  • ORM concepts
  • Defining models
  • Field types (CharField, IntegerField, etc.)
  • Field options (max_length, null, blank, default)
  • Meta options
  • __str__ method

8. Database Migrations

  • makemigrations command
  • migrate command
  • Migration files
  • showmigrations
  • Rolling back migrations
  • Custom migrations

9. Django Admin

  • Automatic admin interface
  • Creating superuser
  • Registering models
  • Admin customization (list_display, search_fields)
  • ModelAdmin class
  • Admin actions

10. QuerySets

  • Manager và QuerySets
  • Creating objects (create, save)
  • Retrieving objects (all, get, filter)
  • Field lookups (exact, iexact, contains, gt, lt)
  • Ordering results
  • Limiting results

11. CRUD Operations

  • Create (INSERT)
  • Read (SELECT)
  • Update (UPDATE)
  • Delete (DELETE)
  • get_or_create()
  • update_or_create()

12. Forms

  • Django Forms
  • Form fields
  • Rendering forms
  • Form validation
  • Cleaned data
  • Error handling

13. Model Forms

  • ModelForm class
  • Automatic form generation
  • fields và exclude
  • Widgets
  • Saving ModelForms

14. Authentication Basics

  • User model
  • Login và logout views
  • login_required decorator
  • User registration
  • Password change
  • Authentication backends

15. Sessions và Cookies

  • Session framework
  • Setting session data
  • Reading session data
  • Session configuration
  • Cookie handling

16. Messages Framework

  • Message levels (debug, info, success, warning, error)
  • Adding messages
  • Displaying messages
  • Message tags

17. Middleware

  • Middleware là gì?
  • MIDDLEWARE setting
  • Request/response cycle
  • Common middleware
  • Custom middleware basics

18. Django Settings

  • settings.py overview
  • DEBUG mode
  • ALLOWED_HOSTS
  • DATABASES configuration
  • SECRET_KEY
  • Environment variables với python-decouple

19. Generic Views

  • TemplateView
  • ListView
  • DetailView
  • CreateView
  • UpdateView
  • DeleteView

20. Testing Basics

  • Django TestCase
  • Writing test cases
  • Testing views
  • Testing models
  • Test client
  • Running tests

21. Model Relationships

  • ForeignKey (many-to-one relationships)
  • OneToOneField (one-to-one relationships)
  • ManyToManyField (many-to-many relationships)
  • Related queries (reverse lookups)
  • on_delete options (CASCADE, PROTECT, SET_NULL)
  • related_name attribute
  • select_related() và prefetch_related()

22. File Uploads & Media Files

  • MEDIA_URL và MEDIA_ROOT
  • ImageField và FileField
  • Pillow library installation
  • File validation (size, type)
  • Handling uploaded files
  • Image thumbnails
  • Serving media files in development

23. Pagination

  • Paginator class
  • Page object methods
  • Template pagination
  • ListView pagination
  • URL parameters (?page=2)
  • Custom pagination
  • Ajax pagination basics

24. Search & Filtering

  • Q objects for complex queries
  • Search across multiple fields
  • OR và AND conditions
  • Search forms
  • Filter with multiple parameters
  • __icontains, __iexact lookups
  • Search optimization

25. Slugs & SEO-Friendly URLs

  • SlugField introduction
  • Auto-generate slugs from title
  • prepopulated_fields in admin
  • Unique slugs handling
  • get_absolute_url() method
  • URL patterns with slugs
  • SEO best practices

26. Email Configuration & Sending

  • EMAIL_BACKEND settings
  • SMTP configuration
  • send_mail() function
  • EmailMessage class
  • HTML emails
  • Email templates
  • Attachments
  • Contact form implementation
  • Email with forms

27. Class-Based Views Advanced

  • FormView
  • get_context_data() override
  • get_queryset() override
  • Mixins (LoginRequiredMixin, UserPassesTestMixin)
  • Multiple mixins
  • Custom generic views
  • Method override patterns

28. Template Advanced Features

  • Template context processors
  • Custom template tags
  • Custom template filters
  • Template fragments
  • Caching template fragments
  • Template best practices

29. Working with Multiple Databases

  • DATABASES configuration
  • Database routing basics
  • Multi-database queries
  • Database migrations for multiple DBs

30. Deployment Preparation

  • Environment variables
  • DEBUG = False settings
  • ALLOWED_HOSTS configuration
  • Static files collection
  • SECRET_KEY security
  • Database configuration for production
  • requirements.txt
  • .gitignore setup

31. Docker & Containerization Basics

  • Docker concepts (Images, Containers, Volumes, Networks)
  • Installing Docker Desktop
  • Docker architecture
  • Benefits of containerization
  • Dockerfile fundamentals
  • Writing Dockerfile for Django
  • Docker image layers
  • .dockerignore file
  • Building và running containers
  • Docker commands (build, run, stop, ps, logs)
  • Container networking basics
  • Volume mounting for development
  • Multi-stage builds

32. Docker Compose for Django

  • Docker Compose introduction
  • docker-compose.yml structure
  • Services definition (web, db)
  • Django + PostgreSQL setup
  • Environment variables in Compose
  • Depends_on và service orchestration
  • Networks trong Compose
  • Volumes for persistence
  • Development vs Production configs
  • docker-compose commands (up, down, logs, exec)
  • Database initialization
  • Running migrations in containers
  • Accessing Django shell in container

33. Deploying Django with Docker

  • Production Dockerfile optimization
  • Gunicorn setup in container
  • Nginx as reverse proxy
  • Static files serving with Nginx
  • Multi-container deployment
  • Docker networking in production
  • Environment management
  • Health checks
  • Container logging
  • Backup strategies
  • Deployment to cloud platforms (DigitalOcean, AWS, Railway)
  • Docker best practices

34. Comprehensive Project: News/Blog Website

Features:

  • User authentication và profile
  • Categories và tags
  • Rich text editor (WYSIWYG)
  • Image uploads
  • Pagination
  • Search functionality
  • Comment system
  • Admin dashboard
  • Contact form with email
  • SEO-friendly URLs
  • Docker setup included
  • docker-compose.yml with PostgreSQL

Structure:

news_website/
├── articles/
│   ├── models.py (Article, Category, Tag, Comment)
│   ├── views.py (List, Detail, Create, Update)
│   ├── forms.py (ArticleForm, CommentForm)
│   └── urls.py
├── accounts/
│   ├── models.py (UserProfile)
│   ├── views.py (Register, Login, Profile)
│   └── forms.py (UserRegistrationForm)
├── pages/
│   ├── views.py (Home, About, Contact)
│   └── forms.py (ContactForm)
├── templates/
├── Dockerfile
├── docker-compose.yml
├── .dockerignore
├── requirements.txt
└── .env.example

35. Practice Project: E-commerce Basic

35. Practice Project: E-commerce Basic

Features:

  • Product catalog với categories
  • Product detail với multiple images
  • Shopping cart (session-based)
  • Simple checkout form
  • Order management
  • Search và filter products
  • Pagination
  • Admin panel
  • Dockerized with PostgreSQL
  • Redis for sessions (optional)

Models:

  • Category
  • Product (ForeignKey to Category)
  • ProductImage (ForeignKey to Product)
  • Order
  • OrderItem (ForeignKey to Order và Product)

Docker Setup:

services:
  - web (Django + Gunicorn)
  - db (PostgreSQL)
  - nginx (Static files)

36. Best Practices & Code Organization

  • Project structure best practices
  • Apps organization
  • Model design patterns
  • View organization
  • Template organization
  • Static files organization
  • Settings management
  • Code reusability
  • DRY principle
  • Documentation
  • Docker best practices
  • Security considerations
  • Performance tips

Prerequisites

  • ✅ Hoàn thành Module 01: Python Basic
  • ✅ Hoàn thành Module 02: Python Advanced (khuyến nghị)
  • Hiểu cơ bản về HTML/CSS
  • Hiểu cơ bản về databases

Thời Gian Học

  • Ước tính: 6-7 tuần (tăng để bao gồm Docker)
  • Thời lượng mỗi bài: 60-90 phút
  • Thực hành: 2-4 giờ/ngày
  • Total lessons: 36 bài học (bao gồm 3 bài Docker)

Projects

Mini Projects (Throughout Course)

1. Blog Application: Simple blog với posts, categories và comments

2. Todo List: Task management với user authentication

3. Contact Form: Form handling với email notification

4. Image Gallery: Upload và display images với pagination

5. Search System: Tìm kiếm và lọc dữ liệu

6. Dockerized App: Simple Django app với Docker Compose

Major Projects (End of Course)

Project 1: News/Blog Website (Comprehensive)

Technologies: Django 4.x, SQLite/PostgreSQL, Bootstrap 5

Features:

  • ✅ User registration, login, logout, profile
  • ✅ Article CRUD với rich text editor
  • ✅ Categories và tags (many-to-many)
  • ✅ Image uploads với thumbnail
  • ✅ Comment system
  • ✅ Search functionality
  • ✅ Pagination
  • ✅ Contact form với email
  • ✅ SEO-friendly URLs (slugs)
  • ✅ Admin dashboard customization
  • ✅ Responsive design

Skills Covered:

  • Model relationships (ForeignKey, ManyToMany)
  • File uploads (ImageField)
  • Forms và validation
  • Generic views
  • Template inheritance
  • Static và media files
  • Email integration
  • Search với Q objects
  • Pagination
  • Authentication
  • Docker containerization
  • PostgreSQL in Docker
  • docker-compose orchestration

Time: 2-3 weeks

Project 2: E-commerce Website (Basic)

Technologies: Django 4.x, PostgreSQL, Bootstrap 5

Features:

  • ✅ Product catalog với categories
  • ✅ Product detail với multiple images
  • ✅ Shopping cart (session-based)
  • ✅ User registration và login
  • ✅ Checkout form
  • ✅ Order history
  • ✅ Search và filter products
  • ✅ Pagination
  • ✅ Admin product management
  • ✅ Responsive design

Skills Covered:

  • Complex model relationships
  • Many-to-many relationships
  • Session management
  • Form processing
  • QuerySet optimization
  • Image galleries
  • Order management
  • Admin customization
  • Docker multi-container setup
  • PostgreSQL + Redis containers
  • Production-ready Docker config

Time: 2-3 weeks

Project 3: Portfolio Website (Personal)

Technologies: Django 4.x, SQLite, Bootstrap 5

Features:

  • ✅ Home page với intro
  • ✅ Projects showcase với filter
  • ✅ Skills section
  • ✅ Blog posts
  • ✅ Contact form with email
  • ✅ Admin management
  • ✅ Responsive và modern design

Skills Covered:

  • Static pages
  • Dynamic content management
  • Form handling
  • Email integration
  • Template customization
  • SEO optimization

Time: 1-2 weeks

Bài Tập

Mỗi bài học sẽ có:

  • ✍️ Exercises: 5-10 bài tập thực hành
  • 🔨 Hands-on Labs: Build features từng bước
  • 📝 Quiz: 10-15 câu hỏi kiểm tra
  • 🎯 Challenge: Bài tập nâng cao
  • 💻 Code Review: Đánh giá code quality

Kết Quả Sau Khóa Học

✅ Kiến Thức & Kỹ Năng:

1. Web Development Fundamentals:

- Hiểu MVT pattern

- URL routing và views

- Template engine

- Forms và validation

- Static và media files

2. Database & Models:

- Django ORM

- Model relationships (ForeignKey, ManyToMany, OneToOne)

- Migrations

- QuerySets và queries

- Database optimization basics

3. User Management:

- Authentication system

- User registration/login

- Sessions và cookies

- Permissions basics

4. Advanced Features:

- File uploads

- Pagination

- Search functionality

- Email integration

- SEO-friendly URLs

- Admin customization

- Docker containerization

- Multi-container orchestration

5. Best Practices:

- Code organization

- DRY principle

- Security basics

- Testing fundamentals

- Docker deployment basics

- Environment management

🚀 Có Thể Xây Dựng:

1. ✅ Blog/News Websites:

- Multiple categories

- Tagging system

- Comments

- Search

- Author profiles

2. ✅ E-commerce Websites (Basic):

- Product catalog

- Shopping cart

- Checkout system

- Order management

- Product search/filter

3. ✅ Portfolio Websites:

- Project showcase

- Skills display

- Contact forms

- Blog integration

- Admin management

4. ✅ Business Websites:

- Company information

- Services pages

- Contact forms

- News/updates

- Image galleries

5. ✅ Landing Pages:

- Product launches

- Event registration

- Email collection

- Contact forms

- Static content

6. ✅ Web Đặc Thù:

- Job boards (basic)

- Directory websites

- Booking systems (simple)

- Review platforms

- Social features (basic)

📊 Tỷ Lệ Hoàn Thành Các Loại Web:

Loại Website Khả Năng Làm Ghi Chú
Blog/News ✅ 95% Hoàn toàn có thể làm professional
E-commerce Basic ✅ 85% Thiếu payment gateway (học ở Advanced)
Portfolio ✅ 100% Hoàn toàn đủ
Landing Page ✅ 100% Hoàn toàn đủ
Business Website ✅ 95% Hoàn toàn có thể
Social Network 🟡 40% Cần Django Advanced (real-time, API)
Marketplace 🟡 60% Cần Django Advanced (payment, complex logic)

🎯 Không Thể Làm (Cần Django Advanced):

  • ❌ Real-time applications (Chat, Notifications)
  • ❌ RESTful APIs (Mobile apps)
  • ❌ Payment gateway integration
  • ❌ Complex authorization systems
  • ❌ Microservices architecture
  • ❌ WebSocket applications
  • ❌ Celery task queues
  • ❌ Advanced caching strategies
  • ❌ GraphQL APIs
  • ❌ Kubernetes orchestration (có Docker basics)
  • ❌ CI/CD pipelines (có Docker basics)

Module Tiếp Theo

Nội dung Django Advanced sẽ bao gồm:

  • 🚀 Django REST Framework - Build APIs cho mobile/SPA
  • 💳 Payment Integration - Stripe, PayPal, VNPay
  • 📨 Celery Task Queue - Background jobs, async tasks
  • 🔐 Advanced Authentication - JWT, OAuth, Social Auth
  • Caching - Redis, Memcached
  • 📡 WebSockets - Django Channels, real-time features
  • 🐳 Docker Advanced - Kubernetes, Docker Swarm, CI/CD
  • 🔍 Elasticsearch - Advanced search
  • 📊 Performance Optimization - Query optimization, profiling
  • 🏗️ Architecture Patterns - Microservices, CQRS
  • 🧪 Advanced Testing - Integration, E2E testing
  • 📈 Monitoring & Logging - Sentry, ELK stack

Phân Biệt Basic vs Advanced:

Feature Django Basic Django Advanced
Scope Single server apps Large-scale systems
Users < 10,000 users 100,000+ users
Features Standard web apps Complex enterprise apps
APIs ❌ No ✅ RESTful + GraphQL
Real-time ❌ No ✅ WebSockets
Payment ❌ No ✅ Multiple gateways
Async Tasks ❌ No ✅ Celery
Docker ✅ Basics ✅ Advanced (K8s, CI/CD)
Deployment ✅ Docker basics ✅ Production-grade
Testing ✅ Unit tests ✅ Full test coverage
Performance ✅ Basic ✅ Optimized

Roadmap Học Tập:

Django Basic (6-7 weeks)
    ↓
    Includes: Docker Basics
    ↓
Build 2-3 Real Projects (2-3 weeks)
    ↓
    Projects with Docker setup
    ↓
Django Advanced (6-8 weeks)
    ↓
    Kubernetes, CI/CD, Microservices
    ↓
Build Production App (4-6 weeks)
    ↓
Deploy & Maintain (Ongoing)

Tổng thời gian: 4-5 tháng để master Django từ cơ bản đến nâng cao!