I am trying to download a file that is stored in the media folder and it seems as it only works when I am writing the full path as:
file_location = '/home/user/user.pythonanywhere.com/media/'
In the settings page on pythonanywhere, the 'media url' points to the same directory. So I don't really understand why I just can't write /media/ instead for the full path.
Has it something to do with my settings.py file? I have these lines there:
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIA_URL="/media/"
Do I need to have these lines at all?
This is my download function:
class RequestFile(APIView):
def get(self, request):
#Returns the last uploaded file
#Remember if deleting files, only database record is deleted. The file must be deleted
obj = FileUploads.objects.all().order_by('-id')
file_location = '/home/user/user.pythonanywhere.com/media/' + str(obj[0].lastpkg)
x = file_location.find("/")
filename = file_location[x+1:]
print(file_location)
print(filename)
try:
with open(file_location, 'rb') as f:
filex_data = f.read()
#print("filex_data= ", filex_data)
# sending response
response = HttpResponse(filex_data, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=' + filename
except IOError:
# handle file not exist case here
response = HttpResponseNotFound('File not exist')
return response
If I go to the url that points to this class I will get the download.
From Django documentation
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: cars/chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'
So in your case something like
obj = FileUploads.objects.first()
try:
with open(obj.name_of_file_attribute.path, 'rb') as f: