我正在使用Django 2.0.1而我试图用另一个响应覆盖Django 404页面。我不想返回常规模板,而是返回JSON响应。
这是我的项目/ urls.py
from django.conf.urls import include
from django.contrib import admin
from django.urls import path
from django.conf.urls import handler404
from django.http import JsonResponse
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('accounts.urls'))
]
def response404(request, status=200, message='Not Found', data=None):
data = {'status': 404, 'message': message, 'data': data}
return JsonResponse(data=data, status=status)
def response500(request, status=500, message='Not Found', data=None):
data = {'status': status, 'message': message, 'data': data}
return JsonResponse(data=data, status=status)
handler404 = response404
handler500 = response505
并在accounts / urls / py
中from django.urls import path
from .views import UserView, AuthenticationView
urlpatterns = [
path('', UserView.as_view()),
path('auth/', AuthenticationView.as_view()),
]
但是404返回它仍然返回基本的Django 404页面,即使我在settings.py文件中将Debug选项更改为True
答案 0 :(得分:2)
处理程序404不应该调用函数,函数的第一个参数是request。将您的代码更改为:
def response(request, status=200, message='Not Found', data=None):
data = {'status': 404, 'message': message, 'data': data}
return JsonResponse(data=data, status=status)
handler404 = response