我想为我的Django网站返回的所有回复添加一些标题。有没有办法做到这一点(除了向render
函数添加包装器?)
答案 0 :(得分:37)
是的,你应该看看middlewares。
yourapp / middleware.py
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['X-My-Header'] = "my value"
return response
yourproject / settings.py
MIDDLEWARE = [
...,
'yourapp.middleware.MyMiddleware',
...,
]
答案 1 :(得分:0)
返回JsonResponse时。
from django.http import JsonResponse
data = {'key','value'} # some data
response = JsonResponse(data,status=200)
response['Retry-after'] = 345 # seconds
response['custom-header'] = 'some value'
return response