user798719 user798719 - 3 months ago 7
Python Question

How do you get djangorestframework to return xml using format suffix?

I can get djangorestframework to return json via a format suffix .json, but not return xml via a .xml suffix

http://127.0.0.1:8000/chat/rooms/.json

[
{
id: 1,
timestamp: "2013-12-05T04:27:42Z",
topic: "important one"
},
{
id: 2,
timestamp: "2013-12-05T04:27:49Z",
topic: "important two"
},
{
id: 3,
timestamp: "2013-12-05T04:27:55Z",
topic: "important three"
},
{
id: 4,
timestamp: "2013-12-05T04:28:01Z",
topic: "important four"
},
{
id: 5,
timestamp: "2013-12-05T06:43:38Z",
topic: "another great stimulating topic"
}
]


http://127.0.0.1:8000/chat/rooms/.xml

{
detail: "Not found"
}


Could anyone tell me what I did wrong, b/c the REST api is clearly working...thanks!

Answer

You need to add the XMLRenderer which is not enabled by default.

To do this in settings have something like this:

REST_FRAMEWORK = {
  'DEFAULT_RENDERER_CLASSES': (
    'rest_framework.renderers.XMLRenderer',
    'rest_framework.renderers.JSONRenderer',
    'rest_framework.renderers.BrowsableAPIRenderer',
  )
}

To set renderers at the view level use the render_classes attribute.

Take a look at the Renderers documentation.

Update: It occurs to me the above is only half the answer. You'll also need to add the xml format suffix, as documented here.

I hope that helps.

Comments