I'd like to add a few headers to all responses that my Django website returns. Is there a way to do this (besides adding a wrapper to the render
function)?
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
Note in Django you write the header name in capitals with underscores instead of dashes, but in the request on the client you must write it using dashes instead of underscores (production web servers will strip out custom headers with underscores in them for security reasons).
A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list [i.e., #(values)] or the header field is a well-known exception (as noted below).
Yes, you should have a look at 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', ..., ]
When returning 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With