Django: filtering expected content type?
<p>Django offers a way to restrict the accepted methods using the <code>@request_http_method</code> decorator, so if a particular view can only respond to a GET request we can do:</p>

<pre><code>@require_http_methods(['GET'])
def only_get(request):
    pass
</code></pre>

<p>Otherwise we get a 403 (FORBIDDEN) response.</p>

<p>However, I would also like to accept a <code>Content-Type</code> of json. If it's not json it should reject the request as well (I am guessing a 403 response would also be the appropriate one).</p>

<p>Does Django have anything similar to the <code>require_http_methods</code> decorator, but for content types? If not, how else could I tackle this scenario?</p>

<p>I do not think that Django has something similar for Content-Type, but you can easily write your Middleware, that would drop requests with wrong Content-Type and then use decorator_from_middleware option.</p>

<p>If you use Django 1.10:</p>

<pre><code>class AllowedContentTypes(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request, *args, **kwargs):
        types = kwargs.pop('types') or ['application/json']
        if request.content_type in types:
            response = self.get_response(request)

        else:
            response = HttpResponse() # your response for wrong content type
        return response 
</code></pre>

<p>and apply it to your view like:</p>

<pre><code>@decorator_from_middleware_with_args(AllowedContentTypes)(types=['application/json'])
def your_view(request):
    ...
</code></pre>

<p>Also, you can use Django REST Framework, there you are able to filter Content-Type using Parsers, JSONParser would only allow application/json content-type for requests. It is also would be more useful to implement REST API for you app.</p>

python django