Django Rest从FileField url获取文件 [英] Django Rest get file from FileField url

查看:1836
本文介绍了Django Rest从FileField url获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个包含FileField的django休息模型。

  media = models.FileField(upload_to ='media /%Y /%m /%d /',null =空白=真)

我还实现了序列化器和ListCreateApiView。在那里我可以上传文件。在POST请求休息服务器上传文件夹中的文件夹并返回我的URL。但是,在获取请求时,服务器将使用该url返回json内容。如果我使用url获取请求,则服务器响应找不到页面。如何使用django休息下载上传的文件?我必须创建单独的视图相同吗?如果是这样,怎么办?



编辑:



生成的网址是

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

解决方案

您必须定义 MEDIA_ROOT MEDIA_URL 并在 urlpatterns 中注册 MEDIA_URL ,以允许Django服务器提供这些文件。



请按照下列步骤操作:



Settings.py 文件:

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

将其附加到您的主要网址中。 py 文件来提供媒体文件:

  from django.conf import设置
从django.conf.urls.static import静态

urlpatterns = [
#...其余的URLconf到这里...
] +小号tatic(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

此外,您不必添加媒体再次出现在 upload_to 属性中,因为它的前缀是 MEDIA_URL,那么url将是 /媒体/媒体/`。



这是一个正确的例子:

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

,媒体网址为:

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


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

解决方案

You have to defined 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 an 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

这篇关于Django Rest从FileField url获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆