Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
DRF, caching for as_view()?

In my view, I often use APIView's as_view() to generate json.

I'd like to cache the response and tried the following but it won't work

def some_complex_view(self, request, *args, **kwargs):
    pass

@method_decorator(cache_page(60, key_prefix='drf'))
def dispatch(self, request, *args, **kwargs):
   return super().dispatch(request, *args, **kwargs)

Then, I call

def my_view(request, *args, **kwargs): 
    json_data = MyViewSet.as_view({'get': 'some_complex_view'})(request, format='json')

    data = {
       'my_data': json_data
    }
    return render(request, 'my_template.html', data)

It correctly caches when I request the view using browser, but it won't when using as_view()

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

There are a few strategies listed in the CBV docs:

Add the decorator in your urls.py route, e.g., login_required(ViewSpaceIndex.as_view(..)) Decorate your CBV's dispatch method with a method_decorator e.g.,

from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class MyViewSet(TemplateView):
    template_name = 'secret.html'

Before Django 1.9 you can't use method_decorator on the class, so you have to override the dispatch method:

class MyViewSet(TemplateView):

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MyViewSet, self).dispatch(*args, **kwargs)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!