21

I have filefield in my django model:

class MyModel(Model):
    file = models.FileField(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!

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

how did you get object_name to that view? what URL params did you use?
The object_name doesn't matter as it simply represents a Django Model object. You can retrieve the object any way you like.
You could also use os.path.basename to filter filename instead of using .split('/'). eg. filename = os.path.basename(object_name.file.name). This will work regardless of OS.
what if the filename is UTF-8 string?
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 }}.

Comments

1

You can do this with a FileResponse like so:

def download_file_view(request, id):
    object = get_object_or_404(MyModel, id)

    # Create FileResponse
    return FileResponse(
        object.file.open(),
        as_attachment=True,
        filename=object.file.name
    )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.