dabadaba
dabadaba

Reputation: 9542

Understanding how Django's cache framework works and dealing with cached pages for different user roles

I am having an issue where pages are not being displayed correctly for a certain user role and I am sure the problem is caching. The page is a partial view of a sports schedule which is loaded with AJAX:

url(pattern, cache_page(CACHE_TIMEOUT)(last_modified(season_modified(dont_vary_on("Cookie")(ScheduleView.as_view()))), name='schedule_partial')

Note that season_modified is a function that retuns the last time the season/schedule was modified. It is used to refresh the cache.

Here is the problem:

When a user browses the schedule page view as an anonymous or non-authorized user, the schedule with the non-authorized bits will be loaded and cached. Then if they log it or switch accounts as a referee, the page should load with several referee-related elements, mainly score inputs so they can keep match scores. However, it seems that the non-authorized cached version of the page is loaded, so they cannot interact with the schedule as they should. The opposite scenario also happens: if a referee views the page and it is cached, then logs out, they will see the authorized page as anonoymous user, when they shouldn't.

However, if I log in with my staff account, or if a schedule admin logs in, the admin/staff version of the page is loaded, which is what we want.

My understanding of how this cache framework works is that once the route is accessed by anyone, the page is generated and cached. From then on, until the cache expires, that cached page is going to be served to everybody. Is that how it works?

That would explain why referees are seeing the wrong page, but... shouldn't admins have the same problem too then? Please help me understand how this works.

And the second point of this question is solving the main issue: how can I load the correct version of the page when a referee user opens it up?

Upvotes: 1

Views: 530

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

Your understanding of how the caching mechanism works is correct. By default if anyone accesses a URL, it will be cached for everyone else.

Since you're not showing the code for dont_vary_on decorator, which isn't a standard Django decorator, we can't tell you why it seems to work for staff (if you're sure they are accessing the same URL).

But basically you need to vary the cache key depending on the HTTP request headers, so that if those headers change, the page is re-rendered. Read about Vary headers. The Django cache middleware honours these headers.

Upvotes: 1

Related Questions