Search code examples
pythondjangodjango-templatesdjango-viewsdjango-cache

How can I render and cache a view programatically in Django?


I have a view in Django that is very slow to render. I'd like to render this view and cache it programmatically but haven't figured out how to do so. Is there any simple way to simply invoke my StatusView and get the markup as a string so I can cache it?

Here's my view with the cache decorator:

class StatusView(ListView):
    template_name = 'network/list.htm'
    context_object_name = 'network'

    def get_queryset(self):
        return Network.objects.filter(date__lte=date.today()).order_by('-id')

    def get_context_data(self, **kwargs):
        context = super(StatusView, self).get_context_data(**kwargs)
        ...
        ...
        return context

    @method_decorator(cache_page(60 * 1))
    def dispatch(self, *args, **kwargs):
        return super(StatusView, self).dispatch(*args, **kwargs)

Halfway there. I've managed to render the view programmatically. Now I just need to cache it.

str(StatusView(request=request).get(request).render())


Solution

  • It took a bit of digging since my Django skills are rusty but I got here:

    from django.middleware.cache import UpdateCacheMiddleware
    from django.utils.cache import learn_cache_key
    from django.http import HttpRequest
    from network.views import StatusView
    
    request = HttpRequest()
    request.META['SERVER_NAME'] = '1.0.0.127.in-addr.arpa' # important
    request.META['SERVER_PORT'] = '8000'                   # important
    request._cache_update_cache = True
    response = StatusView(request=request).get(request)
    cacher = UpdateCacheMiddleware()
    cacher.process_response(request, response).render()