I’m trying to make a script for downloading the uploaded files, on the user’s machine. The problem is that the download simply doesn’t work (it either downloads me an empty file, or gives me some errors).
the last error is:
coercing to Unicode: need string or buffer, FieldFile found
def download_course(request, id):
course = Courses.objects.get(pk = id).course
path_to_file = 'root/cFolder'
filename = course # Select your file here.
wrapper = FileWrapper(file(course))
content_type = mimetypes.guess_type(filename)[0]
response = HttpResponse(wrapper, content_type = content_type)
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)
return response
how can I declare properly the filename so that it will know each time what file to be downloading:
the filename is actually ‘course’ as declared above
Thanks !
edited
I think that you need to extract
pathvalue from FileField object:Why is that:
Let’s say I have (well, I actually have) Model:
ImageWithThumbnailsFieldis subclass of FileField, so it behaves the same way. Now, when I do SELECT:it shows (relative to MEDIA_ROOT) path of stored file. But when I access
logoModel attribute:I get instance of some object. If I try to pass that instance to
os.path.getsize:I get TypeError, like you. So I need file path as string, which can be obtained with
pathattribute:Alternatively, I could get
nameattribute andos.path.joinit with MEDIA_ROOT setting:But that’s unnecessary typing.
Last thing to note: because
pathis absolute path, I need to extract filename to pass it to Content-Disposition header: