Django Rest get file from FileField url

巧了我就是萌 提交于 2020-01-03 04:22:09

问题


I have created a django rest model which includes a FileField.

 media = models.FileField(upload_to='media/%Y/%m/%d/', null=True, blank=True)

I also implemented serializer and ListCreateApiView. There I can able to upload a file. On POST request rest server uploads the file in folder and returns me the url. However, on get request, server return json content with the url. If I use the url for get request, server respond Page Not Found. How to download the uploaded file using django rest? Do I have to create separate view for the same? If so, how to do that?

Edit:

The resulting url is

http://localhost:8000/message/media/2015/12/06/aa_35EXQ7H.svg

回答1:


You have to define MEDIA_ROOT, MEDIA_URL and register MEDIA_URL in urlpatterns to allow Django server to serve these files.

Follow these steps:

settings.py file:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media_root")

Append this in your main urls.py file to serve media files :

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Also, you don't have to add media again in upload_to attribute because it's prepended by MEDIA_URL, then the url will be /media/media/.

Here is a correct example:

media = models.FileField(upload_to='message/%Y/%m/%d/', null=True, blank=True)

and the url of the media will be:

http://localhost:8000/media/message/2015/12/06/aa_35EXQ7H.svg


来源:https://stackoverflow.com/questions/34100743/django-rest-get-file-from-filefield-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!