Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Django view class to either string or response

Tags:

python

django

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 like this:

class TemplateView(View):
    def get(self, request):
        context = self._create_context(request)
        return render_to_response('template.html', context)

    def get_string(self, request):
        context = self._create_context(request)
        return render_to_string('template.html', context)

    def _create_context(self, request):
        context = {}
        # Complex context initialization logic...
        return context

I've wired get to my Django URLs. However, I haven't been able to figure out how to instantiate TemplateView so that I can call get_string from other views.

There must be a better way to go about doing this. Ideas?

Update: I've seen some folks talking about making a request internally and using response.content, which would save me from having to write the get_string method. So, perhaps a better question is: How do I make a request to TemplateView from another view?

like image 325
Trevor Burnham Avatar asked Dec 30 '25 03:12

Trevor Burnham


1 Answers

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.

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

response = TemplateView.as_view()(request, as_string=True)
like image 200
Yuji 'Tomita' Tomita Avatar answered Dec 31 '25 17:12

Yuji 'Tomita' Tomita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!