2

I have some Internet Explorer problems with my Angular 5 app, because in the IE 11 my get-requests to a django-REST backend are cached by the browser. I found a question suggesting to add special cache-control-headers to the response, but I didn't find a working answer how to do it with Django REST. All other browsers I have tested seem to work without problems.

Gurkenkönig
  • 670
  • 12
  • 27

3 Answers3

3

Perhaps you could add the Cache-Control header to all responses using a middleware class.

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

    def __call__(self, request):
        response = self.get_response(request)
        response['Cache-Control'] = 'no-cache'
        return response

and then wire that into your settings.py

MIDDLEWARE = [
    ...

    'your.app.CacheControlMiddleware',

    ...
]

Bear in mind that will apply to all views (all your ModelViewSets), which you may or may not want.

If you want to apply it only to specific view sets, you may be better to override the retrieve() and list() methods in your view sets where you can set the Cache-Control header on the Response. For more info on that see http://www.django-rest-framework.org/api-guide/generic-views/#mixins

Will Keeling
  • 17,949
  • 4
  • 42
  • 49
2

I had the same problem.

Adding the 'Cache-Control' header to the response worked for me.

response = Response()
response['Cache-Control'] = 'no-cache'

An example views.py:

from rest_framework import status
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer

def snippet_list(request):
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)

        response = Response(serializer.data)
        response['Cache-Control'] = 'no-cache'
        return response
craigjames
  • 71
  • 5
0

The other answers have the right idea, but here is a slightly more refined solution.

def disable_cache_middleware(get_response):

    def middleware(request):
        response = get_response(request)
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        return response

    return middleware

The main difference here is that no-store and must-revalidate are included in the header as well. The Mozilla documentation on the header suggests this combination to prevent browser caching. You can read more about the extra header values there.

Secondly, I just find that the function-based middleware results in a bit less boilerplate than the class-based solution in this case.

Levi Payne
  • 327
  • 2
  • 10