Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách thêm Django Debug Toolbar vào dự án

Django Debug Toolbar là công cụ gỡ lỗi phổ biến giúp theo dõi truy vấn database, tốc độ tải trang, và nhiều thông tin hiệu năng khác. Hầu như mọi lập trình viên Django đều sử dụng nó. Hãy xem cách tích hợp.

Ví dụ chi tiết

1. Tạo app

Tạo app tên "myapp".

2. Cài đặt package

pip install django-debug-toolbar

3. Cấu hình settings.py

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

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

INTERNAL_IPS = [
    '127.0.0.1',
]

Thêm debug_toolbar vào INSTALLED_APPS, middleware, và định nghĩa INTERNAL_IPS để toolbar chỉ hiển thị ở localhost.

4. Cấu hình URLs dự án (urls.py)

import debug_toolbar
from django.conf import settings
from django.urls import include, path

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

5. View và URLs của app

views.py:

from django.shortcuts import render

def home(request):
    return render(request, "home.html")

urls.py của app:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
]

6. Template (templates/home.html)

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>success</h1>
    </body>
</html>

Kết quả

Debug Toolbar sẽ xuất hiện ở bên phải màn hình trên mọi endpoint URL, hiển thị thông tin: SQL queries, cache, templates, static files, signals, logging, profiling, v.v.

Cách thêm Django Debug Toolbar vào dự án

Mẹo: Trong production, hãy đảm bảo DEBUG = False và không thêm IP production vào INTERNAL_IPS để tránh rò rỉ thông tin nhạy cảm.