Skip to content Skip to sidebar Skip to footer

Render Django View Class To Either String Or Response

I have a template that I want to be able to both serve directly and embed in arbitrary other templates in my Django application. I tried to create a view class for it that looks li

Solution 1:

I'd follow in django's CBV pattern: it determines via dispatch what method to return. By default based on request.method. Why not based on any other argument passed to dispatch()?

So subclass dispatch and give it a way to determine whether or not to return get_string.

defdispatch(self, request, *args, **kwargs):
    if'as_string'in kwargs:
         return self.get_string(request)        
    returnsuper(TemplateView, self).dispatch(request, *args, **kwargs)

response = TemplateView.as_view()(request, as_string=True)

Post a Comment for "Render Django View Class To Either String Or Response"