Nathan Hoad

Django seemingly caching

July 17, 2011

I’ve had a caching problem with this blog/site since I started using Django. Specifically, it was the default view of my blog! Of course, considering this is a blog, which turns up new content every now and then, I figured caching would be a bad idea, as it meant readers wouldn’t be able to see new posts. I noticed that if I force refreshed the page, or cleared my browser cache, I would see the new content.

Seeing as it worked perfectly in the old PHP version (i.e. no caching or force refreshing), I figured Django was to blame. I asked on Stack Overflow, but apart from setting up caching just to force a cache time of 1 second, I didn’t get an answer.

I posted my question to the Django-users mailing list and was told that if the browser is caching it, then the browser is caching it. It “worked” in PHP because PHP sent cache suppression headers, but obviously Django wasn’t. The Django counterpart is the never_cache decorator. So, using a class-based view and a decorator, I present a fix:

# ...
from django.views.decorators.cache import never_cache
from django.views.generic import ListView

urlpatterns = patterns('getoffmalawn.blog.views',
    (r'^$', never_cache(ListView.as_view(queryset=Post.objects.filter(status__text__exact='Published')))),
    # ...
)

I’m pretty happy I’ve got this working now. Of course this is probably more of a temporary fix, as in the future some kind of caching would be a good idea, but for now I’m happy with it as it is.