Django: how to set content-type header to text/xml within a class-based view?
django, django-class-based-views, http-headers, mime-types
Solution
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)
Problem
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 ```