I have filefield in my django model:
file=models.FileField(verbose_name=u'附件',upload_to='attachment/%Y/%m/%d',max_length=480)
This file will display in the web page with link "http://test.com.cn/home/projects/89/attachment/2012/02/24/sscsx.txt"
What I want to do is when user click the file link, it will download the file automatically; Can anyone tell me how to do this in the view?
Thanks in advance!
Now, open the urls.py file from the Django project and update the file with the following script. The text file will download if the path, 'download/' is used after the base URL. Open the browser and execute the following URL that will open the download dialog box for the user.
Django can be installed easily using pip . In the command prompt, execute the following command: pip install django . This will download and install Django. After the installation has completed, you can verify your Django installation by executing django-admin --version in the command prompt.
You can try the following code, assuming that object_name
is an object of that model:
filename = object_name.file.name.split('/')[-1]
response = HttpResponse(object_name.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
See the following part of the Django documentation on sending files directly: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With