I am running a Django app where I can upload files. Now I want to download the files using requests. I was trying to create a view where the file is downloaded, so I can then make a call with requests. But it doesn't quite work
My model:
class FileCollection(models.Model):
name = models.CharField(max_length=120, null=True, blank=True)
store_file = models.FileField(storage=PrivateMediaStorage(), null=True, blank=True)
creation_date = models.DateTimeField(null=True, blank=True)
My views
def fileview(request, *args, **kwargs):
file = FileCollection.objects.first()
file_path = file.store_file
print(file_path)
FilePointer = open(file_path, "r")
response = HttpResponse(FilePointer, content_type='application/msexcel')
response['Content-Disposition'] = 'attachment; filename=NameOfFile'
return response
It tells me that TypeError: expected str, bytes or os.PathLike object, not FieldFile
If I pass in the url provided in the apiview/admin I get: FileNotFoundError: [Errno 2] No such file or directory
Also tried:
def fileview(request):
path = FileCollection.objects.first()
obj = path.store_file
o = str(obj)
file_path = os.path.join(settings.MEDIA_ROOT, o)
print(file_path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(),
content_type="application/vnd.ms-excel")
response[
'Content-Disposition'] = 'inline; filename=' + os.path.basename(
file_path)
return response
but this gives me ValueError: The view file_storage_api.api.v1.views.fileview didn't return an HttpResponse object. It returned None instead.
Is that the right way to go?
I'm very grateful for help or hints. Thanks so much