Friday, September 1, 2017

Re: Link to download a file



On Aug 31, 2017 8:57 AM, "giuseppe ricci" <peppepegasus@gmail.com> wrote:
Hi guys, I need some help to insert a link to download a file. In a view I read data from a csv file and I show them in a table in a template. Under the table I need to insert, when there are data, 
a link similar as Download data and when user click it, he download the datafile, previously I wrote the same data in a csv file. You can see a part of interested view and the template to show data. 
In the code doesn't download anything.

There's a few ways to handle this. 

1. Your 'download' button could simply be a link back to the same page with an additional GET argument (ie ?download= ). In your view, you would generate the data dict normally. Before you start returning responses though, you would check for the presence of the 'download' GET argument via request.GET.get('download', False). If you get anything but False (meaning they clicked the link), you can tweak the response headers and send back only the data you've gathered:


Depending on what kind of file you are returning, you may need to create an in memory file using StringIO or BytesIO and return that.

If you want to have a separate view handle the file download, simply add something like '/download/' to the end of the URL as another urls.py entry, and assume that the user wants to download the file within the view you specify for your URL. If you do that, I suggest you break out the CSV reading/writing logic (along with and file creation work) in to separate functions from the view so that both views access the data in the same way, they simply render and return it differently.

Another way would be to accept a POST submission through a form and then return the file as I explained above.

-James


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVUz1nG%2BWw%2BHAr2wSLh9DuK-9xnY5CKkbbGpbh4TPLiMg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment