we are using Django1.11 and we are having some problems because our header Content-Type
does not contain the charset
part set to UTF-8. Something like this:
Content-Type: application/json; charset=UTF-8
I want to fix that for all endpoints, so I have thought to include a middleware to run after all midlewares have been run. The problem is that I do not know if that's possible. Any ideas? Or alternative solutions?
CodePudding user response:
You can write a custom middleware like this:
from django.utils.deprecation import MiddlewareMixin
class AllIsJsonMiddleware(MiddlewareMixin):
def process_response(self, request, response):
response['Content-Type'] = 'application/json; charset=UTF-8'
return response
But I don't recommend this. This converts all responses to JSON. Best use a framework like https://www.django-rest-framework.org/.
However, can use a standard view respone...
return HttpResponse(data, content_type='application/json; charset=UTF-8')
... or a custom decorator:
from functools import wraps
def json_response(function):
@wraps(function)
def wrap(request, *args, **kwargs):
response = function(request, *args, **kwargs)
response['Content-Type'] = 'application/json; charset=UTF-8'
return response
return wrap
@json_response
def my_view(request):
# ....