Debugging Tips0%

Debugging Tips

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

Debugging Tips

Diagnosing bugs, tracking down unhandled exceptions, and resolving database locking issues are critical skills for backend engineers. Developing an efficient debugging workflow transforms opaque 500 server crashes into actionable solutions.


1. Understanding Django's Error Traceback

When DEBUG = True, Django displays an interactive debugging page on unhandled exceptions:

Output
┌─────────────────────────────────────────────────────────────┐
│ TypeError at /articles/create/ │
│ 'NoneType' object has no attribute 'username' │
├─────────────────────────────────────────────────────────────┤
│ Request Method: POST │
│ Request URL: http://127.0.0.1:8000/articles/create/ │
│ Django Version: 5.0.2 │
│ Exception Type: TypeError │
├─────────────────────────────────────────────────────────────┤
│ Traceback: │
│ File "/app/articles/views.py", line 42, in create_article │
│ author_name = request.user.profile.username │
│ │
│ Local vars: │
│ request: <WSGIRequest: POST '/articles/create/'> │
│ form: <ArticleForm bound=True, valid=True> │
└─────────────────────────────────────────────────────────────┘

Inspect Local vars at each frame to see the exact state of variables at the moment of the crash.


2. Interactive Debugging with Python breakpoint()

Modern Python 3.7+ includes the built-in breakpoint() function, which automatically pauses server execution and drops into the pdb (Python Debugger) terminal:

Python
# articles/views.py
def complex_financial_calculation(request):
raw_amount = request.POST.get("amount")
# Drop into interactive debugger!
breakpoint()
calculated_tax = float(raw_amount) * 0.18
return JsonResponse({"tax": calculated_tax})

When the request hits this line, your terminal pauses with an interactive prompt:

  • p variable_name: Print variable value.
  • n: Step to next line of code.
  • s: Step into the function currently being called.
  • c: Continue normal execution until next breakpoint.
  • q: Quit debugger immediately.

3. Structured Logging in Django

Never use print() statements for debugging in production codebases; print() lacks timestamps, log levels, and log rotation. Use Python's standard logging module:

Python
# config/settings.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "{levelname} {asctime} [{module}] {message}",
"style": "{",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "verbose",
},
"file": {
"class": "logging.FileHandler",
"filename": BASE_DIR / "logs/django_errors.log",
"formatter": "verbose",
"level": "ERROR",
},
},
"loggers": {
"django": {
"handlers": ["console", "file"],
"level": "INFO",
"propagate": True,
},
"articles": {
"handlers": ["console"],
"level": "DEBUG",
},
},
}

In your views:

Python
import logging
logger = logging.getLogger(__name__)
 
def update_billing(request, user_id):
logger.info(f"Initiating billing cycle for user {user_id}")
try:
...
except PaymentFailedError as exc:
logger.error(f"Billing failed for user {user_id}: {exc}", exc_info=True)

exc_info=True automatically attaches the full exception traceback to the log!


4. Production Error Monitoring with Sentry

In production where DEBUG = False, unhandled exceptions present users with a generic 500 error page. Use Sentry to capture and aggregate production stack traces in real time:

Bash / Terminal
pip install sentry-sdk
Python
# config/settings.py
import sentry_sdk
 
sentry_sdk.init(
dsn=os.environ.get("SENTRY_DSN"),
traces_sample_rate=0.2, # 20% performance telemetry
profiles_sample_rate=0.2,
)

Interactive Quiz

Practice Quiz

Question 1
What built-in Python function pauses execution and drops into the interactive pdb debugger?
Question 2
Why is using print() statements considered an anti-pattern for production server logging?
Question 3
In the pdb debugger prompt, which command continues execution until the next breakpoint?
Question 4
What does exc_info=True accomplish when calling logger.error("Message", exc_info=True)?
Question 5
What tool is standard in production Django environments for real-time error tracking and alerting?
Next Lesson

Django Debug Toolbar

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Unit TestingDjango Debug Toolbar

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext