Reputation: 9532
My site's landing page was being cached for obvious reasons:
url(r'^$', cache_page(7200)(vary_on_cookie(LandingPage.as_view())), name='landing_page')
Now we introduced a new page we'd like that route to redirect to if certain conditions are met, essentially checking if the user has permission on a certain object:
class LandingPage(TemplateView):
def dispatch(self, request, *args, **kwargs):
if has_permission(self.request.user, object):
return redirect('new_page')
return super(LandingPage, self).dispatch(request, *args, **kwargs)
However, since the view is cached, the user won't be redirected if the original landing page was already cached. And viceversa.
What I want is for the view to always run the permission check. If it passes, it should redirect to the new page which shouldn't be cached. If it doesn't, the landing page should be returned, and it should be cached.
Upvotes: 1
Views: 35
Reputation: 2088
You could move the cache_page
call from urls
to the overwritten dispatch
method like so:
class LandingPage(TemplateView):
def dispatch(self, request, *args, **kwargs):
if has_permission(self.request.user, object):
return redirect('new_page')
cached_dispatch = cache_page(7200)(vary_on_cookie(super(
LandingPage, self
).dispatch))
return cached_dispatch(request, *args, **kwargs)
This way the check will always be performed before returning the cached response
Upvotes: 1