[Django]-Django : provide dynamically generated data as attachment on button press

5👍

Solution:

After looking at the problem a little further and talking to a colleague about it, it seems as though my problem lies in trying to pass the response object to the javascript. For those interested, I solved the problem with a little careful re-routing of the data.

views.py

In my views.py I added a couple lines of code in my main view that would set variables of two extra views (one for csv one for json) to the response objects holding the data. These two extra views would then be called when their respective buttons were pressed, returning the httpresponse and prompting the user for download.

#MAIN VIEW FUNCTION
def view(request):
    #Do stuff, get data as string

    #Get data into needed formats 
    jsonData  = jsonToJsonFile(dataString, fileName)

    #Set values to external view ****NEW PART****
    returnJSON.jsonData = jsonData

    #Render main template
    return render_to_response('mainTemplate.html', {'someForm'    : aForm,
                                                    'regularData' : dataString})

#SECONDARY VIEW TO RETURN JSON DATA TO USER ****NEW PART****
def returnJSON(request):
    #Simply return the response
    return returnJSON.jsonData

template.html

Then, when the button is pressed by the user, the anchor is linked via the url to the secondary django view that will present the download option to the user.

<li class = 'button'>
    <a  href = "{% url client.views.returnJSON %}"> 
        JSON
    </a>
</li>

urls.py

Lastly, I just pointed my url patterns to the view.

urlpatterns = patterns('',
    (r'^somesite/$', views.view),
    (r'^somesite/json$',  views.returnJSON),
)

So far, this method has worked great for me! If anyone has any other suggestions, or a better method, I would certainly be open to hear it.

2👍

I think you need to change your javascript to make it start a file download – see this question & answer:
starting file download with JavaScript

Leave a comment