What's Inside Guide
A comprehensive guide to understanding the Django boilerplate architecture. This documentation explains the codebase structure, component relationships, and architectural decisions that make this boilerplate production-ready.
1. Dev Container
Dev Containers provide a consistent, reproducible development environment that runs inside Docker containers. This approach ensures that every team member or machine works with an identical development setup, completely eliminating the notorious "works on my machine" syndrome that plagues traditional development workflows.
You can easily customize your development environment by modifying the configuration file located at .devcontainer/devcontainer.json
. The most common and powerful customization is adding your favorite VS Code extensions, which will be automatically installed for everyone:
- Browse the extensions marketplace in your code editor
- Find your desired extension and click the gear icon
-
Copy the extension ID (usually in format
publisher.extension-name
) -
Add it to the
extensions
array indevcontainer.json
Pro Tip: The dev container includes pre-configured Python tools, Django development server, database connections, and debugging capabilities out of the box.
2. Configuration
All application configuration is strategically centralized in the config/
directory. This architecture follows Django best practices by cleanly separating settings for different environments (development, testing, and production), with environment-specific configurations located in config/settings/
.
Key Configuration Files
asgi.py
Configures the ASGI (Asynchronous Server Gateway Interface) application for handling async operations, WebSockets, and concurrent requests. Use this for modern async Django features, otherwise stick with the traditional WSGI setup.
wsgi.py
The Web Server Gateway Interface configuration for traditional synchronous Django applications. This is the production-ready default that works with most deployment scenarios.
urls.py
The master URL configuration that routes requests throughout your entire Django project. It includes app-specific URLs, admin panel, authentication routes, and handles static/media files during development.
websocket.py
Defines the WebSocket application for real-time features. Includes basic handlers for connection management and message routing. Perfect for building chat systems, live notifications, or collaborative features.
celery.py
Initializes and configures the Celery distributed task queue system. Handles background job processing, scheduled tasks, and long-running operations that shouldn't block web requests.
Environment Settings
Local Settings
Optimized for development with debugging tools and rapid iteration:
- • DEBUG = True - Detailed error pages with stack traces
- • Mailpit integration - Captures all emails for testing at localhost:8025
- • Development tools - Debug toolbar, browser reload, Django extensions
- • DummyCache backend - Disables caching to show fresh data always
- • Docker optimizations - File watching and polling for containers using watchman
Test Settings
Configured for automated testing with speed and reliability:
- • In-memory database - Faster test execution
- • Simplified logging - Reduced noise during test runs
- • No external services - Self-contained test environment
- • Optimized settings - Minimal overhead for test performance
Production Settings
Hardened for live deployment with security and performance focus:
- • Security hardening - HTTPS enforcement, secure cookies, HSTS headers
- • SSL/HTTPS enforcement - Automatic redirects and secure connections
- • Redis caching - High-performance distributed caching layer
- • Sentry integration - Real-time error monitoring and performance tracking
- • Static file optimization - CDN integration and efficient asset delivery
3. Core App
The core app serves as the foundational backbone of your Django project, providing essential functionality, utility functions, and example implementations for you to build your features on top of.
Key Components
Views & URL Patterns
All core app URLs are prefixed with /app
as configured in the root urls.py. This provides clean URL namespacing:
-
• Dashboard (
/app/
) - The main application dashboard and starting point -
• AI Example (
/app/ai-example/
) - Live demonstration of AI integration capabilities (appears if AI was selected during setup) -
• Background Tasks (
/app/background-tasks/
) - Interactive examples of Celery task processing (appears if background tasks were selected)
Security Features
XSS Prevention
All user input is sanitized using Django's escape()
function to prevent Cross-Site Scripting attacks. This ensures malicious scripts cannot be injected into your application.
CSRF Protection
Form submissions are protected using the @require_POST
decorator combined with Django's built-in CSRF middleware to prevent Cross-Site Request Forgery attacks.
Input Validation
Comprehensive input validation checks for empty fields, data types, and content length. All validation errors are handled gracefully with user-friendly messages.
HTMX Integration
Views return HTML fragments instead of full pages, enabling seamless dynamic updates without JavaScript complexity. Perfect for modern, responsive user interfaces.
Established Patterns
The core app demonstrates several important architectural patterns used throughout the project:
- Function-Based Views: Prioritizes simple, readable FBVs over complex class-based views for better maintainability and easier debugging
- Security First: Every user input is escaped and validated before processing, following Django security best practices from the ground up
- Graceful Error Handling: All error conditions return helpful, user-friendly messages rather than exposing technical details or causing crashes
- Asynchronous Task Processing: Long-running operations are offloaded to background workers to keep the web interface responsive
- RESTful URL Design: Clean, descriptive URL patterns with proper app namespacing for better organization and SEO
4. Deployment
The project features an enterprise-grade producton-ready deployment system that seamlessly supports both local development and production environments. Built around Docker and Docker Compose, it provides consistent, reproducible deployments across all stages of your application lifecycle, from initial development through production scaling.
Local Development Environment
Configuration File: docker-compose.local.yml
Core Services
- • Django development server - Auto-reloading web server with debug capabilities
- • PostgreSQL database - Full-featured SQL database with persistent storage
- • Mailpit email testing - Captures and displays all outgoing emails locally
- • Redis & Celery workers - Background task processing (if enabled during setup)
Developer Features
- • Hot reloading - Automatic server restart when code changes
- • Volume mounting - Direct file system access for instant updates
- • Development tools - Debug toolbar, profiling, and code analysis tools
- • Direct port access - Easy debugging and service inspection
Production Environment
Configuration File: docker-compose.production.yml
Production Services
- • Django/Gunicorn server - High-performance WSGI application server
- • PostgreSQL with backups - Production database with automated backup system
- • Redis with persistence - Caching and session storage with data durability
- • Traefik reverse proxy - Load balancing, SSL termination, and automatic certificate management
Production Features
- • Automatic SSL certificates - Let's Encrypt integration with auto-renewal
- • Health monitoring - Service health checks and automatic recovery
- • Performance optimization - Caching, compression, and resource optimization
- • Security hardening - HTTPS enforcement, secure headers, and container isolation
5. Payments
The payments app provides a complete, battle-tested Stripe integration that handles the entire payment lifecycle. It supports subscription management, one-time payments, customer portal access, and comprehensive webhook processing for real-time payment events, ensuring your SaaS can handle complex billing scenarios from day one.
Core Features
Checkout Session Creation
- • Dynamic pricing support - Handles multiple subscription tiers and pricing models
- • Free trial management - Built-in 7-day trial period (fully customizable)
- • User linking - Automatic association of payments with user accounts via metadata
- • Error resilience - Comprehensive error handling with detailed logging for debugging
Subscription Management
Automated subscription lifecycle management with atomic database operations:
-
•
grant_membership()
- Activates user membership immediately after successful payment confirmation -
•
remove_membership()
- Deactivates membership when subscription is canceled or expires -
•
pause_membership()
- Temporarily suspends access due to payment failures or disputes -
•
resume_membership()
- Reactivates membership when payment issues are resolved
Webhook Processing
Real-time event handling that keeps your application synchronized with Stripe's payment events:
Subscription Events
- • checkout.session.completed - Payment confirmation and membership activation
- • customer.subscription.deleted - Subscription cancellation handling
- • customer.subscription.updated - Status changes (active, past_due, etc.)
- • subscription pause/resume - Temporary membership suspension controls
Payment Events
- • async payment processing - Delayed payment confirmations (bank transfers, etc.)
- • dispute management - Automatic chargeback and dispute handling
- • invoice notifications - Upcoming payment reminders and alerts
- • security verification - Cryptographic signature validation for all webhooks
Subscription State Management
The system tracks user subscription status through two boolean fields that provide granular control:
Active Subscription
User has full access to premium features:
-
•
has_membership = True
-
•
membership_paused = False
Paused Subscription
Temporary suspension (payment issues, disputes):
-
•
has_membership = True
-
•
membership_paused = True
No Subscription
Free tier user or canceled subscription:
-
•
has_membership = False
-
•
membership_paused = False
6. Templates & Static Files
The main project directory contains all frontend assets, templates, and project-specific configurations, serving as the presentation layer of your Django application. This organized structure ensures clean separation between backend logic and frontend presentation concerns.
Template System
Base Template (base.html)
- • SEO-optimized meta tags and viewport configuration
- • Google Fonts integration (Inter, Montserrat, Open Sans)
- • Tailwind CSS framework for styling
- • HTMX for dynamic interactions and Alpine.js
- • Mobile-first responsive design approach
Organization Structure
- • Pages: All HTML pages separated by folders for organization
- • Layouts: Special layouts used by core page templates
- • Components: Reusable HTML components
- • Account: Django-allauth template overrides with custom styling
Static Asset Management
CSS System
-
• Source:
jsutils/tailwind.css
-
• Development: compiled to
css/output.css
-
• Production: minified to
css/dist.css
- • Custom Tailwind configuration
JavaScript Utilities
- • Tailwind CSS CLI and packages
- • Build and watch scripts
- • Development workflow optimization
Build Commands
npm run tailwind:watch
# Production build with minification
npm run tailwind:build
7. Users
The users app provides a comprehensive user management system built on Django's robust authentication framework with django-allauth integration. It handles user registration, authentication, profile management, and subscription status tracking, providing everything needed for a professional SaaS user experience.
Custom User Model
Key Features
Email-Based Authentication
- • Simplified user identification
- • Unique email constraint for security
Payment Integration
- • stripe_customer_id for Stripe linking
- • has_membership for subscription status
- • membership_paused for suspension
Simplified Name Field
- • Single name field instead of first/last
- • Accommodates global naming patterns
- • Optional for flexible onboarding
Custom Manager
- • Email validation for user creation
- • Secure password hashing
- • Full type safety with hints
Django-Allauth Integration
Account Adapter
- • Controls user registration availability
- • Configurable via settings
- • Consistent signup flow management
Social Account Adapter
- • Handles social authentication
- • Smart name population from providers
- • Fallback logic for missing data
Security Features
- • Unique email constraints prevent duplicate accounts
- • Normalized email handling for consistency
- • Secure password storage using Django's built-in hashers
- • Proper permission checking and staff validation
- • Optional allauth integration for admin login
8. Styled Admin (Django Unfold)
The boilerplate includes Django Unfold, a modern and beautifully designed admin interface that transforms Django's default admin panel into a professional, user-friendly dashboard. This enhancement provides a significantly improved experience for managing your application's data and configuration.
Key Features
Modern Design
- • Clean Interface: Modern, responsive design with improved typography and spacing
- • Dark Mode Support: Built-in dark/light theme switching for better user preference accommodation
- • Mobile Responsive: Optimized for tablets and mobile devices with touch-friendly controls
- • Improved Navigation: Intuitive sidebar navigation with collapsible sections and search
Enhanced Functionality
- • Advanced Filters: Enhanced filtering options with better UX for complex queries
- • Improved Forms: Better form layouts with enhanced field widgets and validation display
- • Data Visualization: Charts and graphs for better data insights directly in the admin
- • Bulk Actions: Streamlined bulk operations with improved confirmation dialogs
Integration Benefits
User Experience
- • Faster Navigation: Quick access to frequently used models and actions
- • Better Search: Enhanced search functionality across all admin models
- • Customizable Dashboard: Widgets and shortcuts for common administrative tasks
- • Accessibility: WCAG compliant design for better accessibility support
Developer Benefits
- • Easy Customization: Simple configuration options for branding and theming
- • Plugin System: Extensible architecture for adding custom admin functionality
- • Performance: Optimized queries and lazy loading for better admin performance
- • Documentation: Comprehensive documentation for customization and extension
Configuration & Access
Admin Access
Access the enhanced admin interface at /admin/
after creating a superuser account:
python manage.py createsuperuser
Pre-configured Models
The admin interface comes pre-configured with optimized views for:
- • User Management: Enhanced user administration with subscription status visibility
- • Payment Data: Stripe integration data with transaction history and subscription details
- • System Configuration: Easy access to site settings and configuration options
- • Content Management: Streamlined content editing with rich text support
9. Development Tools & Configuration
The project includes a comprehensive suite of modern development tools and configurations optimized for professional Python development with seamless Docker integration. These tools enhance productivity, code quality, and team collaboration.
Just Command Runner
For developers who prefer simplified Docker-based development workflows when not using dev containers, Just provides an intuitive command interface:
Environment Management
just up # Start development environment
just down # Stop environment
just logs # View Docker logs
just rebuild # Rebuild containers
Django Operations
just shell # Django shell
just migrate
# Run migrations
just makemigrations # Create migrations
just test
# Run test suite
Package Management (UV)
Project Configuration
Uses UV for modern Python package management with comprehensive tooling:
- • Python 3.12 with exact version requirements
- • Separate dependency groups for dev/production
- • Lock file for reproducible builds
- • Hash verification for security
Core Dependencies
Production
- • Django 5.2.5
- • Stripe for payments
- • AI libraries (OpenAI, Anthropic)
- • Redis and Celery
- • Django-allauth
Development
- • pytest for testing
- • ruff for linting/formatting
- • mypy for type checking
- • django-debug-toolbar
- • coverage and pre-commit
Tool Configurations
Code Quality
- • Ruff: Fast Python linter and formatter
- • MyPy: Static type checking
- • djLint: Django template linting
- • Coverage: Test coverage analysis
Testing
- • Pytest: Modern testing framework
- • Database reuse for faster tests
- • Django settings integration
- • Import mode optimization
AI Agent Guidelines
Both AGENTS.md
and CLAUDE.md
contain strong guidelines for AI-assisted development:
Development Workflow
- Code Study & Analysis: Examine codebase structure and patterns
- Planning: Break down features and identify dependencies
- Build (TDD): Write tests first, implement minimal code
- Security Review: Input validation, XSS prevention, CSRF protection
- Code Review: Pattern consistency and edge case handling
- Documentation: Implementation summary and usage instructions
Code Style Principles
- • Boring is Better: Predictable, readable code over clever solutions
- • Self-Documenting: Clear variable names, minimal comments
- • Single Responsibility: Each function does one thing well
- • Explicit over Implicit: Clear intentions, no magic numbers
- • Fail Fast: Early input validation and clear exceptions
Additional Features & Components
This guide covers the core architectural components, but the boilerplate contains numerous additional features that extend beyond this documentation. As you work with the codebase, you'll discover helper utilities, middleware configurations, custom template tags, pre-built components, and testing utilities that are designed to be self-explanatory and intuitive.
These undocumented features are intentionally comprehensive and follow established Django patterns. They include performance optimizations, security enhancements, development conveniences, and integration utilities that become apparent through practical usage rather than requiring explicit documentation.
The architecture is designed to reveal its full capabilities progressively as you implement your specific requirements. This approach ensures you have access to a complete development toolkit while maintaining codebase clarity and avoiding documentation overhead for self-evident functionality.
Need Help?
If you encounter any issues understanding the architecture or have questions about the codebase structure, I'm here to help!
I typically respond within 24 hours. Include specific questions about components or architecture patterns for the most helpful guidance.