mdbhal
mdbhal

Reputation: 99

Django: serving user uploaded files

I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = "/media/"

When I access these files through my admin I get the following url displayed in my browser:

http://127.0.0.1:8000/media/filename.pdf

Hence what I tried is to give a link to the file in my HTML code :

<a href="/{{instance.docFile.url}}/">File</a>

But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error.

Adding localhost:8000/ before {{instance.docFile.url}} also didn't work.

Why isn't this working?What is the correct way to display link to my files?

Let me know if anything else is required.Thank you.

Upvotes: 2

Views: 1486

Answers (3)

Jermaine
Jermaine

Reputation: 940

Please see the Django setting MEDIA_ROOT documentation to better understand what your trying to do.

First MEDIA_ROOT and STATIC_ROOT must have different values.

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'

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

See static files documentation for more details.

Second, You need to add these settings to your base urls.py.

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)

If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES in settings.py.

At the top of your HTML page add {% load static %} then to display your media:

<img src="{{ MEDIA_URL }}{{ docFile }}" alt="test">

Please take your time with the Django Documentation, trust me it will help and also checkout the File upload settings

Upvotes: 2

Robert
Robert

Reputation: 3483

in your urls.py

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)

in your settings.py

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

Then in your template

<a href="{{instance.docFile.url}}">File</a>

If you want know refer the docs Manage static files

Upvotes: 3

Akash D
Akash D

Reputation: 789

The error is coming because your file is not stored in media.it is stored in static but your database store media URL. change your MEDIA_ROOT (given below) and try to upload one more time

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Don't put slash :

<a href="{{instance.docFile.url}}">File</a>

Upvotes: 2

Related Questions