3

I have a view called show_board. Inside it, among other things, I increment a field Board.views by 1 every time it is run, to count page views.

The problem is that when I use the @cache_page decorator on that view, Board.views is only going to get incremented every time a new cached view gets generated, and not every time that view is requested, like I want to.

How could I achieve this?

flatterino
  • 1,005
  • 11
  • 21

1 Answers1

3

You can actually write another decorator to achieve this.

def view_incrementer(view_func):
    """A decorator which increments board views"""

    def _wrapped(*args, **kwargs):
        # here you can increment Board.views
        # kwargs will contain URL parameters
        pk = kwargs.get('pk')
        Board.objects.filter(pk=pk).update(views=F('views')+1)
        return view_func(*args, **kwargs)

    return _wrapped

Then apply the decorator to your view function/method:

@view_incrememter
@cache_page(timeout=60)
def show_board(request, pk):
    ...

Or you can use it directly in your urls.py

url(r'^some-path/(?P<pk>\d+)/$', view_incrementer(cache_page(60)(show_board))),
Derek Kwok
  • 12,768
  • 6
  • 38
  • 58
  • 1
    This worked fantastically. I'm a little lost however when it comes to the use of _wrapped inside the decorator: what does `_wrapped` return exactly, and why must it be done in this nested way? Thank you very much. – flatterino Feb 04 '16 at 19:24
  • 1
    _wrapped returns view_func evaluated. Here is a simplified example: `view_incrementer(show_board)` will return _wrapped, where view_func is show_board. When _wrapped is called, board.views in incremented, and show_board is called and returned. – Derek Kwok Feb 04 '16 at 20:26
  • 1
    There is an excellent guide to decorators which may help you understand this answer better at http://stackoverflow.com/a/1594484/386221. Python decorators are a powerful construct and well worth your time to learn :) – Derek Kwok Feb 04 '16 at 20:27
  • This is not working for me, it still changes only when cached page times out, can you help? – yashas123 Feb 18 '19 at 05:51