最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Django : provide dynamically generated data as attachment on button press - Stack Overflow

programmeradmin1浏览0评论

Problem Overview:

I am creating a Django-based client with the intent of returning data from a web service. The goal of this project is to return data to the user from the web service based on the values selected by the user in a form. Upon the form submit, a query string is generated, sent to the web service and the page data is returned as a string. Currently, that data is displayed to the user in the browser. I want to provide the functionality that would allow the user to click a button and download the data.

Question:

How could I return the data to the user when they click a button in their browser for download? How do I make different options of the same data available (i.e. application/json, or text/csv)?

Current (not-working) Implementation:

I am attempting, and failing, to do the following:

views.py

Returning a render_to_response object of my template. To the template I pass the form, and the data in it's various forms.

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

    #Get data into needed formats (see utils.py)
    jsonData  = jsonToJsonFile(dataString, fileName)

    return render_to_response('template.html', {'someForm'    : aForm,
                                                'regularData' : stringData,
                                                'jsonData'    : jsonData...})

utils.py

Contains functions to take the data as a string and return response objects. This part I am unsure if I am doing correctly. I call these functions in the view to get jsonData (and csvData) into their proper formats from the original data string.

def jsonToJsonFile(dataString, fileName):

    #Get the data as json
    theData = json.dumps(dataString)

    #Prepare to return a json file
    response = HttpResponse(theData, mimetype = 'application/json')
    response['Content-Disposition'] = 'attachment; filename=' + str(fileName) + '.json'

    #return the response
    return response 

template.html

I am currently passing the responses into the template. This is where I am really lost, and have not yet begun to find a good solution. I expect I will need to use javascript to return the variables (jsonData and csvData) to the user when the button is clicked. I have attempted the use of the onclick action of the anchor class, and then using javascript to return the django variable of the response - but this really isn't working.

<li class = 'button'>
    <a  href = "#dataButtons" onclick = "javaScript:alert('test');"> 
    TEST
    </a>
</li>
<li class = 'button'>
    <a  href = "#dataButtons"  onclick = "javaScript: var a = '{{ jsonData }}'; return a;"> 
    JSON
    </a>
</li>

I put the test part in there to, well, test whether or no the alert would work. It does. However, when I click the button for the json data, nothing happens.

Am I approaching this pletely wrong? Or is there something small that I am missing?

Problem Overview:

I am creating a Django-based client with the intent of returning data from a web service. The goal of this project is to return data to the user from the web service based on the values selected by the user in a form. Upon the form submit, a query string is generated, sent to the web service and the page data is returned as a string. Currently, that data is displayed to the user in the browser. I want to provide the functionality that would allow the user to click a button and download the data.

Question:

How could I return the data to the user when they click a button in their browser for download? How do I make different options of the same data available (i.e. application/json, or text/csv)?

Current (not-working) Implementation:

I am attempting, and failing, to do the following:

views.py

Returning a render_to_response object of my template. To the template I pass the form, and the data in it's various forms.

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

    #Get data into needed formats (see utils.py)
    jsonData  = jsonToJsonFile(dataString, fileName)

    return render_to_response('template.html', {'someForm'    : aForm,
                                                'regularData' : stringData,
                                                'jsonData'    : jsonData...})

utils.py

Contains functions to take the data as a string and return response objects. This part I am unsure if I am doing correctly. I call these functions in the view to get jsonData (and csvData) into their proper formats from the original data string.

def jsonToJsonFile(dataString, fileName):

    #Get the data as json
    theData = json.dumps(dataString)

    #Prepare to return a json file
    response = HttpResponse(theData, mimetype = 'application/json')
    response['Content-Disposition'] = 'attachment; filename=' + str(fileName) + '.json'

    #return the response
    return response 

template.html

I am currently passing the responses into the template. This is where I am really lost, and have not yet begun to find a good solution. I expect I will need to use javascript to return the variables (jsonData and csvData) to the user when the button is clicked. I have attempted the use of the onclick action of the anchor class, and then using javascript to return the django variable of the response - but this really isn't working.

<li class = 'button'>
    <a  href = "#dataButtons" onclick = "javaScript:alert('test');"> 
    TEST
    </a>
</li>
<li class = 'button'>
    <a  href = "#dataButtons"  onclick = "javaScript: var a = '{{ jsonData }}'; return a;"> 
    JSON
    </a>
</li>

I put the test part in there to, well, test whether or no the alert would work. It does. However, when I click the button for the json data, nothing happens.

Am I approaching this pletely wrong? Or is there something small that I am missing?

Share Improve this question edited Oct 11, 2011 at 22:50 mshell_lauren asked Oct 11, 2011 at 21:54 mshell_laurenmshell_lauren 5,2344 gold badges30 silver badges36 bronze badges 2
  • Can you post the javascript too, because if nothing happens, it should be client-side. If the returned values are wrong are showing up in a page instead of downloading, that would be server-side. – Umur Kontacı Commented Oct 11, 2011 at 22:14
  • the javascript is in the section on my template. Really it is just a line : onclick = "javaScript: var a = '{{ jsonData }}'; return a;" where {{jsonData}} is the django variable of the response. From what i can tell, the values received from the web service are correct. When i render the variable jsonData straight from the view (i.e. return jsonData) it opens the file for downloading as it should and the data is fine - leading me to believe it is probably how i am calling it in the template. – mshell_lauren Commented Oct 11, 2011 at 22:45
Add a ment  | 

2 Answers 2

Reset to default 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.

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

发布评论

评论列表(0)

  1. 暂无评论