Django Python

Setting Up Django in a VS Code Dev Container: A Step-by-Step Guide

Running Django in a Dev Container with VS Code

Running Django in a VS Code dev container is a great way to standardize your development environment while leveraging the power of Docker. With a dev container, you can eliminate “it works on my machine” problems and create a portable development setup. In this tutorial, I’ll walk you through the process of setting up Django in a VS Code dev container.

Prerequisites

Before we start, ensure that you have the following installed:

  1. VS Code: Download and install from code.visualstudio.com.
  2. Docker: Install Docker Desktop (for Windows/macOS) or Docker Engine (for Linux).
  3. Dev Containers Extension: Install the Dev Containers Extension in VS Code.

1. Create Your Project Directory

Start by creating a directory for your Django project.
For this tutorial, we’ll use the directory django-dev-container-test.

mkdir django-dev-container-test
cd django-dev-container-test

2. Initialize the Dev Container


Now we are going to create a dev container that allows us to run and debug the python code we’ll be writing.

A dev container is configured using a .devcontainer folder that contains the configuration files. Let’s create the necessary files:

Create the .devcontainer Folder

mkdir .devcontainer

Create the devcontainer.json

This file tells VS Code how to configure the dev container. Create it inside the .devcontainer folder:

touch .devcontainer/devcontainer.json

Add the following content to devcontainer.json:

{
  "name": "Django Dev Container",
  "dockerFile": "Dockerfile",
  "context": "..",
  "settings": {
    "python.pythonPath": "/usr/local/bin/python",
    "editor.formatOnSave": true
  },
  "extensions": [
    "ms-python.python",
    "ms-python.vscode-pylance",
    "ms-azuretools.vscode-docker"
  ],
  "forwardPorts": [8000],
  "postCreateCommand": "pip install django",
  "remoteUser": "root"
}

This file automates setting up the container and VS Code for you, so you don’t have to configure everything manually every time.

Create the Dockerfile

This file defines the Docker image for your dev container. Create it inside .devcontainer:

touch .devcontainer/Dockerfile

Add the following content to Dockerfile:

# Use an official Python image
FROM python:3.11-slim

# Set up environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    git \
    && rm -rf /var/lib/apt/lists/*

# Create a working directory
WORKDIR /workspace

# Install Python dependencies
COPY requirements.txt /workspace/
RUN pip install --upgrade pip && pip install -r requirements.txt

3. Add requirements.txt

Create a requirements.txt file in the project root to define the Python dependencies:

touch requirements.txt

Add the following line to your requirements.txt file

Django>=5.1.5,<5.2

This will pull the latest stable release of Django (5.1.5 – at time of writing)


4. Open the Project in the Dev Container

  1. Open the django-dev-container-test folder in VS Code.
  2. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS) and search for:
    Dev Containers: Rebuild and Reopen in Container
  3. VS Code will build the container and reopen your project inside it.

5. Create a New Django Project

Once inside the dev container terminal, we will start a new Django Project and the test it by loading it in our browser.

Run the following command to create a new Django project named myproject in the current directory:

django-admin startproject myproject .

Run the Development Server:

python manage.py runserver 0.0.0.0:8000

VS Code will ask you if you want to open the site in your browser, or you can navigate to http://localhost:8000. You should see the default Django welcome page.

VS Code Tips for Django Development

  • Debugging: Set breakpoints in your code and use the Python extension for interactive debugging.
  • Extensions: The ms-python.python and ms-python.vscode-pylance extensions will greatly enhance your coding experience.
  • Hot Reload: Django’s development server automatically reloads when you make changes to your code.

6. SQLite and Setting up the Database

Django uses SQLite as its default database, which is lightweight and requires no additional setup. SQLite stores the database in a single file (db.sqlite3), located in your project directory by default. It is suitable for development and small projects but has limitations in performance and scalability for larger applications.

If you would like to use MySQL or PostgreSQL, I’ll write a followup tutorial explaining how to expand this project to use them.

Apply the Database Migrations

Before we can begin creating tables, we’ll need to run any outstanding migrations remaining from the Django install.

Run the following command to apply the migrations and create the necessary database tables:

python manage.py migrate

7. Create an Admin User

The Django admin interface is a powerful tool for managing your application. To access it, you need to create an admin user:

  1. Open the container terminal in VS Code.
  2. Run the following command to create a superuser:
    python manage.py createsuperuser
  3. You will be prompted to provide the following information:
    • Username: Choose a username for the admin account.
    • Email address: Enter a valid email address.
    • Password: Set a secure password and confirm it.
  4. Once completed, the superuser will be created and saved in the SQLite database.
  5. Start the development server (if not already running):
    python manage.py runserver 0.0.0.0:8000
  6. Access the admin interface by navigating to http://localhost:8000/admin in your browser.
  7. Log in with the credentials of the superuser you just created.

You will now have full access to Django’s admin interface to manage models, users, and more.


Understanding the Configuration Files

devcontainer.json:

The devcontainer.json file provides instructions for VS Code to configure the development environment inside the container. Here’s why these choices were made:

  • name: “Django Dev Container” gives the container a clear and descriptive name, making it easy to identify.
  • dockerFile: Points to the Dockerfile, which defines the container’s underlying environment.
  • context: “..” ensures that the entire project directory (one level above .devcontainer) is available during the build process.
  • settings: Configures Python for the container. Setting python.pythonPath ensures VS Code uses the correct Python interpreter inside the container, and editor.formatOnSave enables consistent code formatting.
  • extensions: Pre-installs useful VS Code extensions, such as:
    • ms-python.python: Python language support.
    • ms-python.vscode-pylance: Advanced Python type checking and IntelliSense.
    • ms-azuretools.vscode-docker: Docker management inside VS Code.
  • forwardPorts: Opens port 8000 so the Django development server running inside the container can be accessed locally via http://localhost:8000.
  • postCreateCommand: Automatically installs Django in the container right after it is built, saving you from manual installation.
  • remoteUser: Sets the user to root for easier file permissions and configuration during development.

Dockerfile:

The Dockerfile defines the environment for running Django. Here’s why specific elements were chosen:

  • Base Image: FROM python:3.11-slim This is a lightweight official Python image is used to reduce the container size while including essential Python features. Python 3.11 is chosen for its performance improvements and new features.
  • Environment Variables: ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1
    • PYTHONDONTWRITEBYTECODE: Prevents Python from generating .pyc files, reducing unnecessary writes to the container.
    • PYTHONUNBUFFERED: Ensures Python output is displayed immediately, which is helpful for debugging.
  • System Dependencies: RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ git \ && rm -rf /var/lib/apt/lists/*
    • build-essential: Provides tools for compiling Python packages with native extensions.
    • libpq-dev: Enables PostgreSQL database connectivity, commonly used in Django projects.
    • git: Adds version control tools directly in the container.
    • Cleanup (rm -rf /var/lib/apt/lists/*) minimizes the container’s final size by removing temporary files.
  • Working Directory: WORKDIR /workspace Defines the default working directory inside the container where your project files will reside.
  • Python Dependencies:
    COPY requirements.txt /workspace/ RUN pip install --upgrade pip && pip install -r requirements.txt
    • Copies requirements.txt into the container and uses it to install Python dependencies.
    • Upgrades pip to ensure compatibility with modern Python packages.

Conclusion

Congratulations! You’ve successfully set up Django in a VS Code dev container. This setup not only ensures consistency across teams but also eliminates configuration headaches by standardizing your development environment. From here, you can expand your project’s capabilities by integrating services like PostgreSQL for database management, Redis for caching, or Celery for task queues. This foundation provides everything you need to start developing Django applications effectively. Happy coding!

To top