我需要在 Django 中编写完整的媒体路径吗?

Do I need to write the full media path in Django?

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

file_location = '/home/user/user.pythonanywhere.com/media/' 

在 pythonanywhere 的设置页面中,'media 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

如果我转到指向此 class 的 url,我将下载。

来自 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'

所以在你的情况下是这样的

  obj = FileUploads.objects.first()
  try:    
      with open(obj.name_of_file_attribute.path, 'rb') as f: