Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Django Pro Template banner

Contributors Forks Stargazers Issues MIT License CI LinkedIn

Django Pro Template



Explore the docs »
· Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. Getting Started
  3. Usage
  4. Contributing
  5. License
  6. Contact

About The Project

A production-ready Django project template with a professional, secure, and scalable architecture.

Built With

  • Python
  • Django
  • Docker

(back to top)

Getting Started

To start this project, follow these steps:

Prerequisites

  • pip: A package management system for Python.

  • venv: A module for creating isolated Python environments.

  • Docker & Docker Compose: To run the project's database.

1. Clone the Repository

Use git clone to download the project files to your local machine, then navigate into the newly created directory:

git clone https://github.com/GstMirabal/Django-Pro-Template.git
cd Django-Pro-Template

(back to top)

2. Install Virtual Environment and Dependencies

  1. Create a virtual environment:

    From the project root directory, run:

    python3 -m venv venv
    
    
  2. Activate the virtual environment:

    • On macOS and Linux:

      source venv/bin/activate
      
      
    • On Windows:

      venv\Scripts\activate
      
      
  3. Install project dependencies:

    With the virtual environment activated, install all required packages:

    pip install -r requirements.txt
    
    

    For local development (linting with ruff), also install the dev dependencies:

    pip install -r requirements-dev.txt
    
    

(back to top)

Initial Configuration

1. Create Environment Variables

Before running the application, you need to set up your local environment secrets.

  1. Create your .env File:

    Navigate to the root of the project. Create a .env file by copying the template:

    cp .env.example .env
    
    
  2. Generate a Django Secret Key:

    Run the following command in your terminal:

    python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
    
    

(back to top)

  1. Complete your .env File:
  • Navigate to the root of the project and copy .env.example to a new file named .env:

    cp .env.example .env
  • Paste the secret key you just generated into the DJANGO_SECRET_KEY variable. Also, fill in any other required values, such as POSTGRES_PASSWORD.

    Note: The SECRET_KEY is essential for the security of your Django project. Never share this key publicly.

(back to top)

  • The .env file should contain the following configuration variables needed to run the project:
# ==============================================================================
#                 ENVIRONMENT VARIABLES TEMPLATE (.env.example)
# ==============================================================================
# This file serves as a template for the required environment variables.
# To set up your local development environment:
#   1. Copy this file and rename it to ".env".
#   2. Fill in the required secret values (e.g., DJANGO_SECRET_KEY, POSTGRES_PASSWORD) in your new ".env" file.
#
# IMPORTANT: This .env.example file IS safe to commit to version control (Git).
# The .env file with your secrets MUST NEVER be committed.
# ==============================================================================


# ==============================================================================
#                       PROJECT & DOCKER COMPOSE SETTINGS
# ==============================================================================
# Base name for the project, used by Docker Compose and documentation.
PROJECT_NAME='YourProjectName'


# ==============================================================================
#                       DJANGO SETTINGS
# ==============================================================================

# DJANGO_SECRET_KEY: Generate a new secret key for your local .env file.
# Command: python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
DJANGO_SECRET_KEY=

# BASE_DIR: Optional override for the project's root path.
# Leave blank for local development to let settings.py calculate it automatically.
BASE_DIR=

# DEBUG: Enables Django's debug mode. Should be "false" in production.
# Only "true"/"false" are accepted (case-insensitive) — any other value
# makes the app refuse to start instead of silently guessing.
DEBUG="True"

# ALLOWED_HOSTS: Comma-separated list of hosts allowed for development.
# In production, this should be your actual domain(s) (e.g., 'api.yourdomain.com').
ALLOWED_HOSTS="localhost,127.0.0.1"

# CORS_ALLOWED_ORIGINS: Comma-separated list of frontend origins allowed in development.
# In production, this should be your frontend's domain (e.g., 'https://app.yourdomain.com').
CORS_ALLOWED_ORIGINS="http://localhost:3000,http://127.0.0.1:3000"

# TRUST_PROXY_SSL_HEADER: Only set to "true" if this app sits behind a
# reverse proxy/load balancer that terminates TLS AND is known to strip any
# client-supplied `X-Forwarded-Proto` header. Leave "false" unless verified.
TRUST_PROXY_SSL_HEADER="false"

# LANGUAGE_CODE / TIME_ZONE: adjust to your own project. Defaults are
# deliberately neutral (UTC) rather than tied to any specific region.
LANGUAGE_CODE="en-us"
TIME_ZONE="UTC"

# CROSS_SITE_FRONTEND: Only set to "true" if your frontend lives on a
# genuinely different registrable domain than this API. Same-site cases
# (different port on localhost, different subdomain) do NOT need this.
CROSS_SITE_FRONTEND="false"


# ==============================================================================
#                       POSTGRESQL DATABASE SETTINGS
# ==============================================================================
# These variables are used by Docker Compose to BUILD the database and by
# Django (via config.toml) to CONNECT to it.

# Choose a name for your local development database.
POSTGRES_DB=your_db_name

# Choose a username for your local database.
POSTGRES_USER=your_db_user

# Choose a secure password for your local database. This is a secret.
# Special characters (!, @, #, etc.) are fine as-is — settings.py URL-encodes
# this value automatically before building the database connection URL.
POSTGRES_PASSWORD=

# Host where the database is running (for local Docker, this is always 'localhost').
POSTGRES_HOST="localhost"

# Standard PostgreSQL port.
POSTGRES_PORT="5432"


# ==============================================================================
#                       PROJECT LOGGING
# ==============================================================================
# Directory where log files will be stored.
PROJECT_LOGS_DIR="logs"


# ==============================================================================
#                       EMAIL SETTINGS
# ==============================================================================
# Not used in development (DEBUG=True) because the console backend is active.
# In production, these must be filled with real SMTP credentials.
EMAIL_HOST=""
EMAIL_PORT="587"
EMAIL_USE_TLS="True"
EMAIL_HOST_USER=""
EMAIL_HOST_PASSWORD=""

1.1 Environment Variable Descriptions

This section explains the required environment variables for the Django-Pro-Template project, as defined in the .env.example file.

Project Metadata

  • PROJECT_NAME: The project's official name for logs and documentation.

Django Settings

  • DJANGO_SECRET_KEY: The cryptographic signing key. Must be kept secret and unique for production.

  • DEBUG: Toggles debug mode. Must be "false" in production. Only "true"/"false" (case-insensitive) are accepted — any other value makes the app refuse to start rather than silently guessing.

  • ALLOWED_HOSTS: A comma-separated list of allowed hostnames.

  • CORS_ALLOWED_ORIGINS: A comma-separated list of permitted frontend origins for API requests. Also becomes CSRF_TRUSTED_ORIGINS and enables CORS_ALLOW_CREDENTIALS, so a decoupled frontend at these origins can authenticate via session cookies.

  • TRUST_PROXY_SSL_HEADER: Only set to "true" if this app sits behind a reverse proxy/load balancer that terminates TLS and is known to strip any client-supplied X-Forwarded-Proto header. Leave "false" unless verified — enabling it blindly lets a client spoof the header.

  • LANGUAGE_CODE / TIME_ZONE: Locale/timezone for this deployment. Defaults are neutral (en-us/UTC) rather than tied to any specific region.

  • CROSS_SITE_FRONTEND: Only set to "true" if your frontend lives on a genuinely different registrable domain than this API (e.g. a SPA on myapp.example calling an API on api.otherdomain.com). Same-site cases (different port on localhost, or a different subdomain of the same domain) do not need this.

PostgreSQL Database Settings

  • POSTGRES_DB: The name of the database.

  • POSTGRES_USER: Username for the database connection.

  • POSTGRES_PASSWORD: Password for the database user. This is a secret and must be set in your .env file.

  • POSTGRES_HOST: The database server host (e.g., localhost).

  • POSTGRES_PORT: The database server port (default: 5432).

Project Logging

  • PROJECT_LOGS_DIR: The directory where log files are stored.

Email Settings

  • EMAIL_HOST, EMAIL_PORT, EMAIL_USE_TLS, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD: Configuration for the production SMTP server (not used when DEBUG=True).

Note: DJANGO_SECRET_KEY and POSTGRES_PASSWORD are crucial for the application to run. In production, all secret variables must be set.

(back to top)

2. Load Environment Variables

To load the environment variables from the .env file, follow these steps:

  1. Ensure your virtual environment is activated:

    For macOS and Linux:

    . venv/bin/activate

    For Windows:

    venv\Scripts\activate
  2. Load environment variables from the .env file:

    For macOS and Linux:

    export $(grep -v '^#' .env | xargs)

    For Windows:

    foreach ($line in Get-Content .env) { 
        if ($line -match "^\s*[^#\s]") { 
            $name, $value = $line -split "=", 2 
            [System.Environment]::SetEnvironmentVariable($name, $value) 
        } 
    }

This will load the environment variables from your .env file into your shell session, ensuring that they are available for your project.

(back to top)

3. TOML Configuration

The central configuration for the Django application is located at the project root (config.toml, not inside backend/). It doesn't exist yet on a fresh clone — create it from the example template:

cp config.toml.example config.toml

This file acts as a template, mapping variables from the .env file to the required settings via the $VARIABLE_NAME syntax. The application will fail to start (ImproperlyConfigured) if config.toml is missing.

The following parameters are configured by default to start the project in a local development environment:

# ==============================================================================
#                      PROJECT METADATA
# ==============================================================================
[project]
name = "{$PROJECT_NAME}"
version = "1.0.0"
description = "A production-ready Django project template with a professional, secure, and scalable architecture."
author = "Gustavo Mirabal"

# ==============================================================================
#                       DJANGO SETTINGS
# ==============================================================================
[django_settings]

# --- Secret key for Django's security. Its value is defined in the .env file ---
# It must be unique for each environment and should never be shared.
DJANGO_SECRET_KEY = "$DJANGO_SECRET_KEY"

# --- Project base path. Optional, used to override the path in environments like Docker ---
BASE_DIR = "$BASE_DIR"

# --- Enables/disables debug mode. Only "true"/"false" are accepted
# (case-insensitive); any other value makes the app refuse to start. ---
DEBUG = "$DEBUG"

# --- Comma-separated list of allowed domains for serving the application ---
# Example in production: "api.yourdomain.com,www.yourdomain.com"
ALLOWED_HOSTS = "$ALLOWED_HOSTS"

# --- Comma-separated list of allowed frontend origins to access the API ---
# Example in production: "https://app.yourdomain.com"
# Also becomes CSRF_TRUSTED_ORIGINS and enables CORS_ALLOW_CREDENTIALS, so a
# decoupled frontend at these origins can authenticate via session cookies.
CORS_ALLOWED_ORIGINS = "$CORS_ALLOWED_ORIGINS"

# --- Only set to "true" if this app sits behind a reverse proxy/load
# balancer that terminates TLS AND is known to strip any client-supplied
# `X-Forwarded-Proto` header. Leave "false" unless you have verified this. ---
TRUST_PROXY_SSL_HEADER = "$TRUST_PROXY_SSL_HEADER"

# --- Locale/timezone for this deployment. Defaults are neutral (UTC) if left
# blank; adjust to your own project instead of editing settings.py. ---
LANGUAGE_CODE = "$LANGUAGE_CODE"
TIME_ZONE = "$TIME_ZONE"

# --- Only set to "true" if your frontend lives on a genuinely different
# registrable domain than this API. Same-site cases do NOT need this. ---
CROSS_SITE_FRONTEND = "$CROSS_SITE_FRONTEND"

# ==============================================================================
#                       DATABASE COMPONENTS
# ==============================================================================
# This section defines the individual components of the database connection.
# The values are substituted from the .env file.
# The final DATABASE_URL is then assembled within the settings.py file for maximum control.
[DB]

# --- Name of the database to be created by Docker and used by Django ---
POSTGRES_DB = "$POSTGRES_DB"

# --- Username for the database connection ---
POSTGRES_USER = "$POSTGRES_USER"

# --- Password for the database user. The actual value is a secret in .env ---
# Special characters are fine as-is — settings.py URL-encodes this value
# automatically before building the database connection URL.
POSTGRES_PASSWORD = "$POSTGRES_PASSWORD"

# --- Hostname or IP address of the database server ---
# For the local Docker setup, this is always 'localhost'.
POSTGRES_HOST = "$POSTGRES_HOST"

# --- Port on which the database server is listening ---
# The standard port for PostgreSQL is 5432.
POSTGRES_PORT = "$POSTGRES_PORT"
  • Remember to adjust values like ALLOWED_HOSTS and CORS_ALLOWED_ORIGINS in your .env file when moving to a production environment.

  • The file also contains sections for email ([email_settings]) and logging ([project_logging]) configuration, which are also populated from the .env file.

Note: The config.toml file is designed to be version-controlled (committed to Git) and contains no secrets. It uses the $VARIABLE_NAME syntax to dynamically load sensitive values from the .env file. Ensure your .env is correctly filled out before starting the project.

(back to top)

4. Database Initialization

To set up the database and apply the initial application schema, follow the detailed steps below. This process uses Docker to run the PostgreSQL database and Django commands to create the necessary tables.

  1. Start the Docker Desktop Application. Before running any commands, ensure that the Docker Desktop application is open and running on your system. You should see the Docker whale icon in your system's menu bar or tray with a green indicator, which signifies that the Docker daemon is active and ready.

  2. Launch the Database Container. From the project's root directory (where the docker-compose.yml file is located), run the following command in your terminal:

docker-compose up -d db
  • What this command does: Docker Compose reads the docker-compose.yml and .env files. On its first run, it downloads the official PostgreSQL image, creates a container, and automatically initializes the database (POSTGRES_DB), user (POSTGRES_USER), and password (POSTGRES_PASSWORD) that you defined in your .env file. The -d flag runs the container in the background (detached mode).

  • docker-compose.yml also defines a backend service (this Django app, built from the repo's Dockerfile) — running db on its own here, by name, keeps this local setup exactly as before (Django runs outside Docker via venv for faster iteration). To run everything containerized instead (docker-compose up -d, no arguments, starts both services), see docs/guides/CORE_DEPLOYMENT_GUIDE.md.

2.1. Verify the Container is Running (Optional). To confirm that the database container has started successfully:

docker ps

You should see a container named Django-Pro-Template_db (or the name you configured) in the list with the status Up.

  1. Apply Database Migrations. Once the database container is running, the next step is to create the internal table structure (the schema) that the Django application requires. Navigate to the backend directory:
cd backend

CRITICAL WARNING: Custom User Model

This template intentionally does not include a custom user model to provide maximum flexibility. Before you run python manage.py migrate for the first time, you MUST create your own user app and set the AUTH_USER_MODEL in settings.py.

Failure to do so will lock your project into Django's default user model, which is extremely difficult to change later.

# Example of creating a user app
cd backend
python manage.py startapp users

Then, create your model in users/models.py and add AUTH_USER_MODEL = 'users.User' to settings.py.

Run the migration commands in sequence:

# This command creates the migration files (the "blueprints") based on your models
python manage.py makemigrations

# This command applies the migrations to create the tables in the database
python manage.py migrate
  • Expected Output: After running migrate, you will see a list of all migrations being applied, with an OK next to each one. This confirms that the tables have been created in your PostgreSQL database.

With the tables in place, the next step is to create a superuser to access the Django admin.

(back to top)

5. Creating a Superuser

To access the admin interface, you need to create a superuser account. Follow these steps:

  1. Open a terminal and navigate to your project directory.
  2. Run the following command:
    python manage.py createsuperuser
  3. Follow the prompts to enter your desired username, email, and password.

Once created, you can log in to the admin interface at http://0.0.0.0:8000/admin using the superuser credentials. /admin/login/ is protected against brute-force attempts by django-axes: after 5 failed attempts, the (username, IP) pair is locked out for an hour.

(back to top)

6. Run the Server

Finally, run the following command to start the application's local server:

  1. Ensure your virtual environment is activated:

    source venv/bin/activate  # On Windows use: venv\Scripts\activate
  2. Start the server:

    python manage.py runserver

The server should be running at http://0.0.0.0:8000 or the port specified in your configuration.

(back to top)

7. Log file

A .log file will be generated the first time you start the server to save all the errors and warnings encountered.

(back to top)

Usage

Once the server is running, you have successfully completed the most critical phase of the project: the setup of a robust and professional infrastructure.

The project is now in a state of a professional "blank canvas". You have at your disposal:

  • A running development server connected to a PostgreSQL database.
  • A secure and production-ready configuration (settings.py) that handles secrets, security headers, brute-force login protection (django-axes), and logging.
  • A modular application structure (apps/) ready to house your business logic.
  • A complete testing framework ready to verify your code.
  • CI on every push/PR (.github/workflows/ci.yml): lint (ruff), tests, and a manage.py check --deploy run that boots the app with DEBUG=false to catch production-config regressions before they reach a real deployment.

From this point on, you have a solid foundation to start building the application's core logic. This includes, but is not limited to:

  • Defining your data models in the different models.py files.
  • Creating your API endpoints in the views.py and urls.py files.
  • Implementing complex business logic and services.
  • Connecting to external services and APIs.

The foundation is complete. It's time to start building.

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

See CONTRIBUTING.md for the full guide (local setup, checks to run before opening a PR, commit conventions). This project follows the Code of Conduct.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

License

Distributed under the MIT License. See LICENSE.txt for more information.

(back to top)

Contact

Gustavo Mirabal Suarez gst.mirabal@gmail.com

Project Link: https://github.com/GstMirabal/Django-Pro-Template

(back to top)

About

A production-ready Django project template with a professional, secure, and scalable architecture.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages