DEV Community

Cover image for Step-by-Step Guide: Setting Up VS Code Debugging for Django Projects
Prodigius
Prodigius

Posted on

Step-by-Step Guide: Setting Up VS Code Debugging for Django Projects

Debugging Django applications with print statements and logs can be time-consuming and inefficient. This tutorial will walk you through setting up a complete debugging environment in Visual Studio Code that allows you to inspect variables, step through code, and understand your application's execution flow in real-time.

Prerequisites

Before we begin, ensure you have:

  • Visual Studio Code installed
  • Python extension for VS Code installed
  • A Django project with a virtual environment
  • Basic familiarity with Django project structure

Step 1: Prepare Your Project Structure

First, navigate to your Django project root directory. Your project should look similar to this:

your-django-project/
├── .venv/                 # Virtual environment
├── manage.py
├── config/
│   ├── settings.py
│   └── __init__.py
├── apps/
└── requirements.txt
Enter fullscreen mode Exit fullscreen mode

Open this directory in VS Code by running:

code /path/to/your-django-project
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure the Python Interpreter

  1. Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P)
  2. Type "Python: Select Interpreter"
  3. Choose the Python executable from your virtual environment (usually .venv/bin/python or .venv/Scripts/python.exe on Windows)

You should see the selected interpreter in the VS Code status bar at the bottom.

Step 3: Create VS Code Workspace Settings

Create a .vscode folder in your project root:

mkdir .vscode
Enter fullscreen mode Exit fullscreen mode

Create .vscode/settings.json with the following content:

{
    "python.defaultInterpreterPath": ".venv/bin/python",
    "python.terminal.activateEnvironment": true,
    "python.testing.pytestEnabled": true,
    "python.testing.unittestEnabled": false
}
Enter fullscreen mode Exit fullscreen mode

This ensures VS Code uses your virtual environment consistently.

Step 4: Create Debug Configurations

Create .vscode/launch.json with these debug configurations:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Django: Debug Server",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "runserver",
                "0.0.0.0:8000"
            ],
            "django": true,
            "justMyCode": false,
            "env": {
                "DJANGO_SETTINGS_MODULE": "config.settings"
            }
        },
        {
            "name": "Django: Debug Tests",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "test"
            ],
            "django": true,
            "justMyCode": false
        },
        {
            "name": "Django: Shell",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "shell"
            ],
            "django": true,
            "console": "integratedTerminal"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Save this file. You should now see these configurations in the Run and Debug panel.

Step 5: Test Your Basic Setup

  1. Open manage.py in your editor
  2. Click in the gutter next to line 2 to set a breakpoint (a red dot should appear)
  3. Press F5 or go to Run > Start Debugging
  4. Select "Django: Debug Server" from the dropdown
  5. The debugger should start and pause at your breakpoint

If everything is working, you'll see the debug toolbar and execution will pause at the breakpoint.

Step 6: Set Up Your First Real Breakpoint

Let's create a simple view to test debugging:

Create or open a views file (e.g., apps/core/views.py):

from django.http import HttpResponse
from django.shortcuts import render

def debug_test_view(request):
    user_name = request.GET.get('name', 'Anonymous')
    breakpoint()  # This will pause execution
    greeting = f"Hello, {user_name}!"
    return HttpResponse(greeting)
Enter fullscreen mode Exit fullscreen mode

Add this to your URLs configuration:

# In your urls.py
from django.urls import path
from apps.core.views import debug_test_view

urlpatterns = [
    path('debug-test/', debug_test_view, name='debug_test'),
    # ... other patterns
]
Enter fullscreen mode Exit fullscreen mode

Step 7: Test Interactive Debugging

  1. Start the debug server (F5, select "Django: Debug Server")
  2. Open your browser and navigate to http://localhost:8000/debug-test/?name=John
  3. The execution should pause at the breakpoint() line
  4. In the VS Code debug console, try these commands:
   user_name
   request.GET
   request.method
Enter fullscreen mode Exit fullscreen mode
  1. Press F5 to continue execution

Step 8: Explore Debug Features

While paused at a breakpoint, explore these debugging features:

Variables Panel

  • Expand request to see all request data
  • Check user_name value
  • Examine local and global variables

Debug Console

Try these commands in the debug console:

# Check request data
request.GET.get('name')
request.META['REQUEST_METHOD']

# Test Django ORM (if you have models)
from django.contrib.auth.models import User
User.objects.count()
Enter fullscreen mode Exit fullscreen mode

Step Controls

  • F10: Step over (execute current line)
  • F11: Step into (enter function calls)
  • Shift+F11: Step out (exit current function)
  • F5: Continue execution

Step 9: Debug Django Tests

Create a simple test file apps/core/tests.py:

from django.test import TestCase
from django.test.client import Client

class DebugTestCase(TestCase):
    def test_debug_view(self):
        client = Client()
        breakpoint()  # Pause here during test
        response = client.get('/debug-test/?name=TestUser')
        self.assertEqual(response.status_code, 200)
        self.assertIn('TestUser', response.content.decode())
Enter fullscreen mode Exit fullscreen mode

To debug this test:

  1. Set a breakpoint in the test method
  2. Press F5 and select "Django: Debug Tests"
  3. The test will run and pause at your breakpoint

Step 10: Advanced Debugging Techniques

Conditional Breakpoints

  1. Right-click on a breakpoint
  2. Select "Edit Breakpoint"
  3. Add a condition like user_name == 'John'

The breakpoint will only trigger when the condition is true.

Debugging Model Operations

# In a model method or view
from apps.core.models import MyModel

def create_user_profile(request):
    breakpoint()
    user = MyModel.objects.create(
        name=request.POST.get('name'),
        email=request.POST.get('email')
    )
    # Step through to see the save operation
    return redirect('success')
Enter fullscreen mode Exit fullscreen mode

Debugging Form Validation

from django import forms

class ContactForm(forms.Form):
    email = forms.EmailField()

    def clean_email(self):
        email = self.cleaned_data.get('email')
        breakpoint()  # Examine email validation
        if not email.endswith('@company.com'):
            raise forms.ValidationError('Invalid domain')
        return email
Enter fullscreen mode Exit fullscreen mode

Step 11: Troubleshooting Common Issues

Issue: Breakpoints Not Working

Solution:

  1. Verify you're running the debug configuration (not just python manage.py runserver)
  2. Check that the Python interpreter is correctly set
  3. Ensure justMyCode is set to false

Issue: Module Import Errors

Solution:

  1. Confirm your virtual environment is activated
  2. Check the Python interpreter path in VS Code status bar
  3. Verify DJANGO_SETTINGS_MODULE is set correctly

Issue: Database Connection Errors

Solution:

  1. Check your .env file or environment variables
  2. Ensure database services are running
  3. Verify Django settings configuration

Step 12: Create a Debug Test Script

Create debug_verification.py in your project root:

import os
import django

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

def verify_debug_setup():
    print("Starting debug verification...")
    breakpoint()  # This should pause execution
    print("Debug setup is working correctly!")

    # Test Django imports
    from django.conf import settings
    print(f"Django settings loaded: {settings.DEBUG}")

if __name__ == '__main__':
    verify_debug_setup()
Enter fullscreen mode Exit fullscreen mode

Run this with the debugger to verify your setup is working.

Next Steps

Now that your debugging environment is configured:

  1. Practice setting breakpoints in your actual Django views
  2. Explore the Variables panel during request processing
  3. Use the debug console to test Django ORM queries interactively
  4. Try debugging your Django tests to understand test execution flow

Conclusion

You now have a complete Django debugging setup in VS Code. This configuration will significantly improve your development workflow by providing real-time insight into your application's behavior. The ability to inspect variables, step through code execution, and interactively test code will help you identify and resolve issues more efficiently than traditional print-statement debugging.

Remember to commit your .vscode/launch.json and .vscode/settings.json files to your repository so your team can benefit from the same debugging setup.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.