问题描述
我已经创建了一个包含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 registerMEDIA_URL
inurlpatterns
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 inupload_to
attribute because it's prepended byMEDIA_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获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!