Search code examples
djangofileserve

Serving media files in Django


I am running Django in development. In settings.py I have set up the MEDIA_URL

MEDIA_ROOT = os.path.join(BASE_DIR, 'fileuploader/uploaded_files')
MEDIA_URL = 'fileuploader/uploaded_files/'

Then in ursl.py I have,

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

As far as I understand this should mean that any url media/filename will serve the file instead just requesting it.

In the template, through the model i am able to get to the file name and url. But i can't make this into a linkable path to download the file.

<p>File URL link <a href="media{{ item.upload.name }}">media{{ item.upload}}</a></p>

Incidently item.upload and item.upload.name produce the same string. The file name in the filestore is ./TESTFILE.txt Do I need to strip the './' at the beginning?

Commit 26 is the project https://github.com/shanegibney/djangoForum

Thanks


Solution

  • I added the MEDIA_URL tag and this allows files to download.

    <p>URL <a href="/{{ MEDIA_URL }}{{ item.upload.name}}">media{{ item.upload}}</a></p>
    

    Also in urls.py to the end I added,

    urlpatterns = [
       ......
        ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)