我是否需要在Django中写入完整的媒体路径?

我是否需要在Django中写入完整的媒体路径?,django,django-media,Django,Django Media,我正在尝试下载存储在媒体文件夹中的文件,它似乎只有在我将完整路径写入以下文件时才起作用: file_location = '/home/user/user.pythonanywhere.com/media/' 在Pythonywhere的设置页面中,“媒体url”指向同一目录。所以我真的不明白为什么我不能写/media/来代替完整的路径 这与我的settings.py文件有关吗?我有以下几行: MEDIA_ROOT= os.path.join(BASE_DIR, 'media') MEDIA

我正在尝试下载存储在媒体文件夹中的文件,它似乎只有在我将完整路径写入以下文件时才起作用:

file_location = '/home/user/user.pythonanywhere.com/media/' 
在Pythonywhere的设置页面中,“媒体url”指向同一目录。所以我真的不明白为什么我不能写/media/来代替完整的路径

这与我的settings.py文件有关吗?我有以下几行:

MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIA_URL="/media/"
我需要这些线路吗

这是我的下载功能:

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
如果我转到指向此类的url,我将从Django获得下载。


下载文件的确切含义是什么?给我们展示一个如何使用媒体文件的示例我现在添加了下载功能。谢谢你,我的新好朋友。这就像一场梦。我的投票不可见,因为我的排名仍然很低。现在标记为接受答案。
>>> 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'
  obj = FileUploads.objects.first()
  try:    
      with open(obj.name_of_file_attribute.path, 'rb') as f: