嗨,我正在尝试调试POST
请求没有导致工具栏显示的问题,对于任何其他GET
请求,调试工具栏显示得很好,似乎没有对其他用户来说是个问题,所以我想知道是否有什么原因导致工具栏无法触发,或者这不是受支持的功能。
这只发生在从 django rest 框架向ViewSets
、 ModelViewSet
提出的请求时,似乎工作得很好,我怎么知道出了什么问题?
我将从这里开始https://github.com/jazzband/django-debug-toolbar/blob/master/debug_toolbar/middleware.py#L58 ,分别使用SHOW_TOOLBAR_CALLBACK
。
我不确定为什么 POST 请求会被工具栏忽略?
这是我解决此问题的中间件:
def Fix_XMLHttpRequest(get_response):
def middleware(request):
# When `POST`ing data from the DRF browsable API, it will set the
# header `X_REQUESTED_WITH: XMLHttpRequest`. (Not sure if the browser
# adds that header of if DRF's front-end does, but that doesn't matter,
# the header is there.) It's a little contradictory that the header is
# there since the browser also requests that the response be 'text/html'.
# Anyway, that's fine except for one thing. Django Debug Toolbar will
# not show the debug toolbar whenever that header is set on the request!
#
# See:
# - https://github.com/jazzband/django-debug-toolbar/blob/c201ce34cea3ba4ce99d1642db17f2cb31c6204e/debug_toolbar/middleware.py#L59
# - https://docs.djangoproject.com/en/2.1/_modules/django/http/request/#HttpRequest.is_ajax
#
# My workaround is to remove that header whenever the request explicitly
# asks for 'text/html'. Again, in my opinion, that header doesn't really
# make sense anyway when the browser wants to receive HTML back.
#
# This makes is so that when you POST data from the DRF browsable API,
# you can still see the Django Debug Toolbar. It maintains the desired
# behavior of _not_ showing the toolbar when you POST from Javascript
# to obtain JSON data.
if 'text/html' in request.META.get('HTTP_ACCEPT', ''):
if request.META.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest':
del request.META['HTTP_X_REQUESTED_WITH']
response = get_response(request)
return response
return middleware
请务必在 Django 调试工具栏的中间件 _before_ 添加该中间件。
我不确定它是否可以。 我正在尝试使用多种方法来捕获发布请求,但仍然无法捕获,这意味着如果您使用 'get' 方法在网站上使用请求,显然没问题。 我使用 Django 的目的是为移动客户端开发服务器,大多数请求方法是 'POST' 。 希望大家帮帮我,不胜感激。
对我有用的(结合 Django REST Framework 的可浏览 API)是这个django-debug-toolbar-history 。
django-debug-toolbar-history使用可浏览的 DRF 开发人员页面也对我有用。
这使我能够跟踪 POST 期间使用的 SQL 查询。
关闭历史面板已发布。 我还确认对于返回的 POST 请求和 HTML 响应,会显示首次亮相的工具栏。
如果您更新到最新版本并继续遇到错误,请重新打开并提供新的详细信息。 谢谢。
最有用的评论
这是我解决此问题的中间件:
请务必在 Django 调试工具栏的中间件 _before_ 添加该中间件。