简体   繁体   中英

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.

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM