Creating a file and returning it to Django in a view

741 views Asked by At

I am trying to build a KML file on the fly for a user to download. I am playing with a KML library in python to produce and save KMLs but I want to return the file as ad ownload. Essentially if a user in my app clicks a link bam the KML is generated and downloaded by the user clicking the link. The code I have isn't working and I am guessing my response is not set up correctly:

in views.py:

def buildKML(request):
    # Create the HttpResponse object with the appropriate PDF headers.

    response = HttpResponse(content_type='application/kml')
    response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"'
    #just testing the simplekml library for now
    kml = simplekml.Kml()
    kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])  # lon, lat, optional height
    kml.save('botanicalgarden.kml')

    return response

The error I get running this method when I click the link or goto the link:

No results - Empty KML file

I assume it is because the filename= and the final that is saved are not one in the same.

1

There are 1 answers

0
Renjith Thankachan On BEST ANSWER

for simplekml module there is a function to get kml as string instead of saving as file, so first initialise response from kml string & return HttpResponse object

kml = simplekml.Kml()
kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])
response = HttpResponse(kml.kml())
response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"'
response['Content-Type'] = 'application/kml'
return response