Django Rest get file from FileField url

2019-06-07 20:38发布

问题:

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