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
Open this directory in VS Code by running:
code /path/to/your-django-project
Step 2: Configure the Python Interpreter
- Open the Command Palette (
Ctrl+Shift+P
orCmd+Shift+P
) - Type "Python: Select Interpreter"
- 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
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
}
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"
}
]
}
Save this file. You should now see these configurations in the Run and Debug panel.
Step 5: Test Your Basic Setup
- Open
manage.py
in your editor - Click in the gutter next to line 2 to set a breakpoint (a red dot should appear)
- Press
F5
or go to Run > Start Debugging - Select "Django: Debug Server" from the dropdown
- 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)
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
]
Step 7: Test Interactive Debugging
- Start the debug server (F5, select "Django: Debug Server")
- Open your browser and navigate to
http://localhost:8000/debug-test/?name=John
- The execution should pause at the
breakpoint()
line - In the VS Code debug console, try these commands:
user_name
request.GET
request.method
- 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()
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())
To debug this test:
- Set a breakpoint in the test method
- Press F5 and select "Django: Debug Tests"
- The test will run and pause at your breakpoint
Step 10: Advanced Debugging Techniques
Conditional Breakpoints
- Right-click on a breakpoint
- Select "Edit Breakpoint"
- 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')
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
Step 11: Troubleshooting Common Issues
Issue: Breakpoints Not Working
Solution:
- Verify you're running the debug configuration (not just
python manage.py runserver
) - Check that the Python interpreter is correctly set
- Ensure
justMyCode
is set tofalse
Issue: Module Import Errors
Solution:
- Confirm your virtual environment is activated
- Check the Python interpreter path in VS Code status bar
- Verify DJANGO_SETTINGS_MODULE is set correctly
Issue: Database Connection Errors
Solution:
- Check your
.env
file or environment variables - Ensure database services are running
- 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()
Run this with the debugger to verify your setup is working.
Next Steps
Now that your debugging environment is configured:
- Practice setting breakpoints in your actual Django views
- Explore the Variables panel during request processing
- Use the debug console to test Django ORM queries interactively
- 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.