Question

I've got a small snippet that I want in my sidebar. The snippet will be visible on each page, and while cheap to fetch (about 50ms on my super-slow netbook!), will change so infrequently that I'd quite like to cache it (partly because I've yet to use Django's cache framework, and I'd like to learn).

I'm not sure what the best way to go here is - middleware or a custom template tag? I'm not sure how easy it would be to implement caching with these approaches. This is such a standard thing to want to do (that is, fragment caching of a fragment visible on each page) that I'm sure there's a Djangonic way to do it, but I can't find what it is.

How do you do it?

Was it helpful?

Solution

I don't think you need to use middleware. A custom template tag would work for this. Since you're doing something like a status message, it would be unrelated to whatever the current view is, so the tag is definitely appropriate.

Just set up the cache back-end (this is very easy to do) and you will have access to cache.set() and cache.get() methods which you can use to store, and retrieve your status message. Be sure to clear the cache whenever the status message is updated.

OTHER TIPS

This sounds perfect for Template fragment caching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top