django-debug

When the user needs to debug a Django application, diagnose errors, set up logging, or use developer tools. Use when the user says "debug," "error," "500 error," "exception," "traceback," "logging," "Django Debug Toolbar," "shell_plus," "print debugging," "pdb," "breakpoint," "why is this failing," "not working," "unexpected behavior," "ImproperlyConfigured," "DoesNotExist," "IntegrityError," "CSRF," "403," "404," or "500." For performance-specific debugging, see django-performance.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "django-debug" with this command: npx skills add ristemingov/django-claude-setup/ristemingov-django-claude-setup-django-debug

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:

  1. Read the full traceback — the actual error is usually at the bottom
  2. Check DEBUG = True in development (shows detailed error pages)
  3. Check Django version compatibility with the package causing the error
  4. Check migrationspython manage.py migrate --check
  5. Check settingspython 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:

CommandAction
nNext line
sStep into function
cContinue
p varPrint variable
pp varPretty-print variable
lList current code
qQuit
hHelp

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.CsrfViewMiddleware is in MIDDLEWARE
  • For AJAX: set the X-CSRFToken header from document.cookie
  • For APIs: use DRF's SessionAuthentication which 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

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

django-auth

No summary provided by upstream source.

Repository SourceNeeds Review
General

django-views

No summary provided by upstream source.

Repository SourceNeeds Review
General

django-admin

No summary provided by upstream source.

Repository SourceNeeds Review
django-debug | V50.AI