Sachin
Sachin

Reputation: 3782

How to prevent the request object from being cached in Django

I am using memcached for caching in my django project and I have view like this

def questions(request):
    # code to fetch all questions

The function does nothing other than return a list of questions from the database, however to the page that it renders the result has a header in which I show the request.user name.

If I directly use @cache_page decorator then the request object is also getting cached and the request.user on that page is also fetched from the cache. As a result I am seeing someone else's name when I go to the questions page.

Is there a way that I can prevent the request object from getting cached, using a decorator. One way is to use the low level api and cache the querysets that I want to cache, but is it possible to write a decorator that will not cache anything related to the request object?

I hope my question is clear.

Upvotes: 0

Views: 424

Answers (1)

Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

Think about modify template for you page, so you can cache one block based on user

{% load cache %}
{% cache 500 sidebar request.user.username %}
    .. sidebar for logged in user ..
{% endcache %}

and other block was the same for all users

{% cache 500 questions %}
    .. questions list ..
{% endcache %}

Take a look at Django Template fragment caching docs

Upvotes: 3

Related Questions