2

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 
2
  • Did you define MEDIA_URL and MEDIA_ROOT? Could you show us what your url looks like? and which server do you use? Commented Dec 5, 2015 at 13:11
  • I have not defined MEDIA_URL and MEDIA_ROOT. Is it necessary to define? Commented Dec 6, 2015 at 2:17

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.