19

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!

Angelia
  • 333
  • 1
  • 3
  • 9

2 Answers2

33

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

Victor Neo
  • 3,042
  • 1
  • 17
  • 13
6

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage

All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You'll most likely want to use the convenience url function provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.

jpic
  • 32,891
  • 5
  • 112
  • 113