Django:如何在基于类的视图中将content-type标头设置为text/xml? [英] Django: how to set content-type header to text/xml within a class-based view?

查看:441
本文介绍了Django:如何在基于类的视图中将content-type标头设置为text/xml?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过这种方式进行操作,但这是行不通的.

I'm trying to do it this way, but it doesn't work.

class MyView(View):

    def options(self, request, *args, **kwargs):
        """
        Handles responding to requests for the OPTIONS HTTP verb.
        """
        response = http.HttpResponse()
        if self.kwargs.has_key('xml'):
            response['Content-Type'] = 'text/xml; charset=utf-8'
        return response

推荐答案

我认为关键点是django.views.generic.base中的render_to_response,其代码是这样的:

I think the key point is render_to_response in django.views.generic.base , whose code is this:

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.

    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)   # key
    return self.response_class(
        request=self.request,
        template=self.get_template_names(),
        context=context,
        **response_kwargs
    )

对于您的情况,可能需要以下代码:

As for your case, May be you need this code:

class MyView(ListView):
    def get(self, request, *args, **kwargs):
        context = self.get_context_data()

        if self.kwargs.has_key('xml'):
            return self.render_to_response(context, content_type="text/xml; charset=utf-8")
        return self.render_to_response(context)

这篇关于Django:如何在基于类的视图中将content-type标头设置为text/xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆