vkris
vkris

Reputation: 2165

Render an xml to a view

The scenario goes like this.

I get an atom file from a website (say A). A third party will be request this atom file through my website (say B).

I am writing a Django app which will frequently poll website A and store it as a file. Now, when a third party requests for the file through website B, I will have to display the file as xml in the browser.

My question is how do I render an entire xml file to a view in Django?

 render_to_response

expects a template. I can't use a template as such. I just need to display the file in the view. How do I do this?

Upvotes: 16

Views: 26781

Answers (5)

tinyhare
tinyhare

Reputation: 2401

Just define the MIME type to 'text/xml' using the content_type argument.

return render(request, 'xmltemplate.xml', {'foo':'bar'}, content_type='text/xml')

In the xmltemplate.xml render the variables if you want.

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <foo>{{ foo }}</foo>
</note>

Upvotes: 2

silent1mezzo
silent1mezzo

Reputation: 2932

Do something like the below:

return render(request, 'myapp/index.html', {"foo": "bar"}, content_type="application/xhtml+xml")

Upvotes: 19

NEFEGAGO
NEFEGAGO

Reputation: 281

return render(request, 'products.xml', content_type='text/xml')

The render function can also work; you must add like jdelos' answer, simply adding the content_type='text/xml'.

Upvotes: 4

Jdelos
Jdelos

Reputation: 211

You just need to define the MIME type to 'text/xml' using the content_type argument:

return HttpResponse(open('myxmlfile.xml').read(), content_type='text/xml')

Upvotes: 21

Daniel Roseman
Daniel Roseman

Reputation: 599708

If you don't want to render a template, don't do so. render is just a shortcut to render a template. If you just want to display text, just pass it into the HttpResponse.

Since your data is in a file, this will work:

return HttpResponse(open('myxmlfile.xml').read())

although you should beware of concurrency issues, if more than one person is accessing your site at a time.

Upvotes: 6

Related Questions