Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · Django Testing & Debugging
Interview question

How do you use Python's pdb / breakpoint() to debug a Django view? Django व्यू को डिबग करने के लिए Python के pdb / breakpoint() का उपयोग कैसे करें?

Answer

Inserting Python's built-in breakpoint() (available since Python 3.7, invoking pdb by default) directly inside a view function pauses execution at that exact line when the request hits it, dropping into an interactive debugger in the terminal running the dev server, where you can inspect variables, step through code line by line, and evaluate expressions in the current scope.

This is especially useful for bugs that only reproduce with a real request (session state, middleware-modified request objects, complex queryset chains) where print-statement debugging is slow and imprecise. It only works with Django's synchronous development server (runserver), not in a production WSGI/ASGI deployment, and must be removed before committing since it would hang any request that reaches it.

def product_detail(request, pk):
    product = Product.objects.get(pk=pk)
    breakpoint()  # execution pauses here; inspect `product`, `request`, etc.
    return render(request, 'product_detail.html', {'product': product})

Python के बिल्ट-इन breakpoint() (Python 3.7 से उपलब्ध, डिफ़ॉल्ट रूप से pdb इनवोक करता है) को सीधे व्यू फंक्शन के अंदर डालने से, जब रिक्वेस्ट उस लाइन पर पहुँचती है, तो एक्ज़ीक्यूशन उसी लाइन पर रुक जाता है, और डेव सर्वर चलाने वाले टर्मिनल में एक इंटरैक्टिव डिबगर खुलता है।

यह उन बग्स के लिए विशेष रूप से उपयोगी है जो केवल वास्तविक रिक्वेस्ट के साथ पुनः उत्पन्न होते हैं। यह केवल Django के सिंक्रोनस डेवलपमेंट सर्वर के साथ काम करता है, प्रोडक्शन डिप्लॉयमेंट में नहीं, और कमिट करने से पहले हटाया जाना चाहिए।

def product_detail(request, pk):
    product = Product.objects.get(pk=pk)
    breakpoint()
    return render(request, 'product_detail.html', {'product': product})

Was this answer clear?