Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีติดตั้ง Django Debug Toolbar สำหรับ Debug แอปพลิเคชัน

Django Debug Toolbar เป็นเครื่องมือ Debug ที่นิยมมาก สำหรับตรวจสอบ Database Queries, Performance, Request/Response, Templates, และอื่นๆ

ขั้นตอนการติดตั้งและตั้งค่า

1. ติดตั้งแพ็กเกจ

pip install django-debug-toolbar

2. เพิ่มใน settings.py

INSTALLED_APPS = [
    # ...
    'debug_toolbar',
    'myapp',
]

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    # ...
]

# ระบุ IP ที่อนุญาตให้เห็น Toolbar
INTERNAL_IPS = [
    '127.0.0.1',
]

3. เพิ่ม URL ใน urls.py ของโปรเจกต์

import debug_toolbar
from django.urls import include, path

urlpatterns = [
    # ...
    path('__debug__/', include(debug_toolbar.urls)),
    path('', include('myapp.urls')),
]

4. สร้าง View และ Template ทดสอบ

# views.py
from django.shortcuts import render

def home(request):
    return render(request, "home.html")
# urls.py (ใน app)
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]
<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1>success</h1>
</body>
</html>

การใช้งาน

รันเซิร์ฟเวอร์และเปิดหน้าเว็บ จะเห็น Toolbar แสดงอยู่ด้านขวาของหน้าจอ คลิกเพื่อดูรายละเอียด:

  • SQL: ดู Query ทั้งหมดที่รันใน Request นี้
  • Templates: ดู Template ที่ใช้และ Context
  • Cache: ข้อมูล Cache operations
  • Signals: Signals ที่ถูกส่ง
  • Logging: Log messages
  • Profiling: Performance profiling

เคล็ดลับ

  • ใช้ DEBUG = True ใน settings.py
  • สำหรับ Docker/Remote: เพิ่ม IP container ใน INTERNAL_IPS
  • สามารถปิด/เปิด Panel ได้ในการตั้งค่า