Proposal: Simplifying Cache Control with a Built-in Mixin or Middleware

Hi everyone,

While working on Django projects, I noticed that implementing proper cache control on views, especially for sensitive content like login pages or user-specific data, can be a bit cumbersome. While the @never_cache decorator is a great tool for views, I was wondering if Django could benefit from a built-in solution.

For example:

  1. A built-in CacheControlMixin:
    A mixin that could handle cache control settings out-of-the-box for class-based views. It could accept configurable attributes for cache directives, making it more versatile.
  2. Cache Control Middleware:
    Middleware that enforces global cache control rules, with the ability to exclude specific views (similar to the login_not_required attribute in the new LoginRequiredMiddleware).
  3. Integration with Django settings:
    Adding cache control settings directly to settings.py could make it easier to enforce default rules in the application, while still allowing fine-grained control at the view level.

What are your thoughts on introducing one of these solutions (or a similar approach) into Django core? I’d love to hear the community’s thoughts and see if others have encountered similar challenges.

I look forward to your feedback and ideas!

Best regards,
Matteo

1 Like

Welcome @trottomv !

It is common practice for proposals such as this to first be created and distributed as a third-party package. This allows for people to take a look at it and to try it, to see if it does satisfy a particular need. This also allows for some time for the code and APIs to be stabilized at a rate more appropriate for a new feature.

Thank you @KenWhitesell for the helpful suggestion! I’ll work on creating a third-party package to explore and refine this idea, and will share it for feedback once it’s ready.

here it is GitHub - trottomv/django-never-cache: A lightweight Django package to simplify Cache-Control configuration for sensitive views.

1 Like