Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django partially caching a view

I have a simple page with the parts:

  • a list of items taken from the database
  • a header.

On the header lies the usual "login form" or the name of signed-in user. For all the users the "items part" is the same, but if I cache the whole view, the different header (your own username or login form if you're not signed-in) is not shown according to the user state. How can I cache the "items" part and leave the header dynamic? Thanks.

like image 473
pistacchio Avatar asked Feb 21 '23 10:02

pistacchio


2 Answers

Use template fragment cache. It allows you to cache only a fragment of a template with your item list:

{% load cache %}
 A header here
{% cache 500  %}
   List of items here
{% endcache %}
like image 160
Mariusz Jamro Avatar answered Mar 04 '23 03:03

Mariusz Jamro


If you're using Django's cache system and version 1.3, it looks like this is very easy with template fragment caching. In fact, the version given in the docs suggests caching both parts of the page as separate fragments, keying the header to the logged-in user:

{% load cache %}

{% cache 500 header request.user.username %}
    .. header ..
{% endcache %}

{% cache 500 items %}
    .. items ..
{% endcache %}
like image 40
nrabinowitz Avatar answered Mar 04 '23 03:03

nrabinowitz