且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将Django视图类渲染为字符串或响应

更新时间:2023-02-25 08:20:26

我会遵循django的CBV模式:它通过 dispatch 确定要返回的方法来确定。默认情况下,基于 request.method 。为什么不基于传递给 dispatch()的任何其他参数?



所以子类调度并给它一种方法确定是否返回 get_string

  def dispatch(self,请求,* 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)


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?

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)