django-debug
SKILL.md
Django Debugging
You are a Django debugging expert. Your goal is to quickly diagnose and fix issues in Django applications.
Initial Assessment
Check for project context first:
If .agents/django-project-context.md exists, read it for the Django version, installed apps, and settings structure.
Immediate Diagnostic Steps
When something is broken, check in this order:
- Read the full traceback — the actual error is usually at the bottom
- Check
DEBUG = Truein development (shows detailed error pages) - Check Django version compatibility with the package causing the error
- Check migrations —
python manage.py migrate --check - Check settings —
python manage.py check --deploy(production issues)
Django Debug Toolbar
The most important dev tool — shows SQL queries, template context, cache hits, signals.
pip install django-debug-toolbar
# settings/dev.py
INSTALLED_APPS += ['debug_toolbar']
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware'] + MIDDLEWARE
INTERNAL_IPS = ['127.0.0.1']
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': lambda request: True, # Always show
}
# urls.py
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns = [path('__debug__/', include(debug_toolbar.urls))] + urlpatterns
Use it to: inspect SQL queries (spot N+1s), see template context, check cache usage, time each panel.
Django Shell
# Standard shell
python manage.py shell
# Better: shell_plus (auto-imports all models)
pip install django-extensions
python manage.py shell_plus
# With SQL logging
python manage.py shell_plus --print-sql
Useful in shell:
# Test a queryset
from articles.models import Article
qs = Article.objects.filter(status='published').select_related('author')
print(qs.query) # See raw SQL
print(qs.explain()) # See query plan
# Check settings
from django.conf import settings
print(settings.DATABASES)
print(settings.INSTALLED_APPS)
# Test email sending
from django.core.mail import send_mail
send_mail('Test', 'Body', 'from@example.com', ['to@example.com'])
Logging Configuration
# settings.py — Development
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG', # Log all SQL queries
'propagate': False,
},
'myapp': { # Your app's logger
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
},
}
Using logging in your code:
import logging
logger = logging.getLogger(__name__)
def some_view(request):
logger.debug('Processing request: %s', request.path)
try:
result = do_something()
logger.info('Completed successfully: %s', result)
except Exception as e:
logger.exception('Unexpected error in some_view') # Includes traceback
raise
Using breakpoint() / pdb
def my_view(request):
articles = Article.objects.all()
breakpoint() # Drops into Python debugger here
return render(request, 'list.html', {'articles': articles})
Key pdb commands:
| Command | Action |
|---|---|
n |
Next line |
s |
Step into function |
c |
Continue |
p var |
Print variable |
pp var |
Pretty-print variable |
l |
List current code |
q |
Quit |
h |
Help |
Common Django Errors
ImproperlyConfigured
django.core.exceptions.ImproperlyConfigured: ...
- Check
INSTALLED_APPS,MIDDLEWARE,TEMPLATES,DATABASES - Check for missing environment variables
- Run
python manage.py check
DoesNotExist / MultipleObjectsReturned
# Prevent DoesNotExist crashes
article = Article.objects.filter(pk=pk).first() # Returns None if not found
# Or:
from django.shortcuts import get_object_or_404
article = get_object_or_404(Article, pk=pk)
IntegrityError
Usually means a unique_together, unique=True, or NOT NULL constraint violation.
- Check the full error message for which constraint failed
- Check your migration history for constraint definitions
CSRF Verification Failed (403)
- Ensure
{% csrf_token %}is in all POST forms - Ensure
django.middleware.csrf.CsrfViewMiddlewareis in MIDDLEWARE - For AJAX: set the
X-CSRFTokenheader fromdocument.cookie - For APIs: use DRF's
SessionAuthenticationwhich handles CSRF, or exempt with@csrf_exempt
Circular Import
# In models.py — use string references for ForeignKey
author = models.ForeignKey('users.User', on_delete=models.CASCADE)
# In code — import inside function to break circle
def some_function():
from other_app.models import OtherModel
...
Migration Conflicts
# See state of migrations
python manage.py showmigrations
# Detect conflicts
python manage.py migrate --check
# Merge conflicting migrations
python manage.py makemigrations --merge
Checking App Health
# Check for common configuration issues
python manage.py check
python manage.py check --deploy # Production-specific checks
# Validate templates
python manage.py validate_templates
# Show URLs
python manage.py show_urls # Requires django-extensions
Sentry (Production Error Monitoring)
pip install sentry-sdk
# settings/prod.py
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn=env('SENTRY_DSN'),
integrations=[DjangoIntegration()],
traces_sample_rate=0.1,
send_default_pii=False,
)
Related Skills
- django-performance: Django Debug Toolbar for query profiling
- django-deployment: Production logging configuration
- django-tests: Writing tests to reproduce and fix bugs
Weekly Installs
3
Repository
ristemingov/dja…de-setupFirst Seen
6 days ago
Security Audits
Installed on
cline3
gemini-cli3
github-copilot3
codex3
kimi-cli3
cursor3