简体   繁体   中英

How to add media_root and media_url in Django

I am using Django 3, and I have tried every solution available on the inte.net, but none of them worked for me. When I set DEBUG=False, I am unable to display an image on the HTML page. Here are my settings

-root_app
--main_app
---settings.py
---asgi.py
---urls.py
---wsgi.py
--sub_app
---admin.py
---urls.py
---views.py
---static
----style.css
---templates
----home.html
---media
----images

media path in settings.py

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

Here what I have done to resolve it

  • add context_processor django.template.context_processors.media'
  • add +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in url_patterns of urls.py of sub_app
  • I changed static storage to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' , otherwise I got 500 error. Check this comment

But still, I am unable to display the image at home.html page. When I click on image source using inspect element, I got this /media/images/img.png

These settings resolved the issue Media Path

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

Static Path

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

Adding re_path line in urls.py of main_app

from django.conf.urls.static import static
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('sub_app.urls')),
    re_path(r'^media/(?P<path>.*)$', serve, kwargs={'document_root': settings.MEDIA_ROOT})
]

Change this

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

to

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

in settings.py and use

{{MEDIA_URL}}images/image.png

inside your template.

An edit to Dr. Abhishek's answer: yes, you need the MEDIA_ROOT setting, but you need to append it into the STATICFILES_DIRS list also, which will look something like this:

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

STATICFILES_DIRS = [
    # ...
    os.path.join(BASE_DIR, 'media'),
]

When you load the image, use a soft-encoded path like this:

{% load static %}
<!-- remember to change the file name/type! -->
<img src="{% static 'images/image.jpg' %}" alt="Image">

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