【问题标题】:Do I need to write the full media path in Django?我需要在 Django 中编写完整的媒体路径吗?
【发布时间】:2020-08-24 10:11:37
【问题描述】:

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

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

在 pythonanywhere 的设置页面中,“媒体 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 django-media


【解决方案1】:

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

【讨论】:

  • 谢谢我的新朋友。这就像做梦一样。
  • 我的投票不可见,因为我的排名仍然很低。现在标记为已接受的答案。
猜你喜欢
  • 2020-04-25
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多