[Django]-How can you use the @cache_page decorator with Django class based views?

5👍

You can use the method_decorator to decorate the view’s dispatch() method, according to the docs. The most succinct way is like this:

from django.utils.decorators import method_decorator
from django.views.generic import ListView

@method_decorator(cache_page(60*60), name='dispatch')
class MyListView(ListView):
    # Your view code here.

2👍

use it in urls.py

url(r'^home_url/?$', cache_page(60*60)(HomeView.as_view())),
👤Serjik

1👍

The method_decorator approach should work just fine (we are using it in our project). Are you sure this is the problem?

this is the code we are using (with names changed) – seems like yours

class MyClassView(CommonMixin, View):
    @method_decorator(cache_page(60*60, cache='cache1'))
    def get(self, request):
                .....
👤eran

1👍

Let us say we want to cache the result of the myView view –

from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def myView(request, year, month):
    text = "Displaying articles of : %s/%s"%(year, month)
    return HttpResponse(text)

and urls.py will be

urlpatterns = patterns('myapp.views',url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/', 'myView', name = 'articles'),)

Leave a comment