djangodjango-cache

Django caches user object


Our websites sometimes has around 600 authenticated users trying to register for an event in a timeframe of 5 min. We have a VPS with 1 CPU and 1GB ram. On these moments the site slows down and gives a 502 error.

For that reason I'm using per-site cache with FileBasedCache. This works excellent and stress tests work fine.

But, when people login, they're redirect to their profile. This is the code:

class UserRedirectView(LoginRequiredMixin, RedirectView):

    permanent = False

    def get_redirect_url(self):
        return reverse("users:detail", kwargs={"membership_number": self.request.user.membership_number})

the user is redirect to an url with their membership_number

class UserDetailView(LoginRequiredMixin, DetailView):

    model = User
    slug_field = "membership_number"
    slug_url_kwarg = "membership_number"

Some users are reporting that they are redirected to someone else his/her profile after logging in.

How does this work? How to prevent user specific parts of the website to be cached? e.g. users also see a list of events that are specific to the groups they are in. In other words, every user should see a different list.

Any ideas? Best practices?


Solution

  • you should be able to vary cache on cookie so that logged in users (assuming cookie based auth) get another cache key.

    from django.views.decorators.vary import vary_on_cookie
    @vary_on_cookie
    def my_view(request):
        pass
    

    https://docs.djangoproject.com/en/dev/topics/cache/#controlling-cache-using-other-headers and https://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers