Django: Downloading uploaded files

我的梦境 提交于 2019-12-13 12:44:52

问题


I have form details in this question Django: Adding files to a form gives multiple argument error

How to download the uploaded file. When i go to edit view of the form, i can see uploaded file url, but its not downloading. What setting to be changed for development and production mode?

Error upon clicking link:

Page not found (404)
Request Method:     GET
Request URL:    http://127.0.0.1:8000/media/Certificate.docx

Using the URLconf defined in tiktant.urls, Django tried these URL patterns, in this order:

    ^ ^$ [name='home']
    ^ ^login/$ [name='login']
    ^ ^logout/$ [name='logout']
    ^ ^logout_then_login/$ [name='logout_then_login']
    ^ ^dashboard/$ [name='dashboard'] 
The current URL, media/Certificate.docx, didn't match any of these.

回答1:


The media url is not showing in the root urls.py file. You need to add the below code in the urls.py file to enable the same.

if settings.DEBUG:
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Note: Please don't forget to add the MEDIA_ROOT and MEDIA_URL in settings.py file. For downloading a file, you need to write some more code.




回答2:


make sure you added the following lines in your project settings.py

import os 
def root(x):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',x)
MEDIA_ROOT = root('media')
MEDIA_URL = '/media/'
TEMPLATE_CONTEXT_PROCESSORS = (
    '-----------------------'
    'django.core.context_processors.media',

)

urls.py

from django.conf.urls import patterns, include, url
from django.conf import settings

urlpatterns += patterns('',url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),

)


来源:https://stackoverflow.com/questions/40396738/django-downloading-uploaded-files

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