'[django]when debug=false,MEDIA_URL returns not found
when DEBUG=TRUE,media_url is working,but DEBUG = False ,returns not working.
This is my setting file.
setting.py
DEBUG = False
...
MEDIA_URL = "/pics/"
MEDIA_ROOT = BASE_DIR
urls.py
urlpatterns = [
....
....
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
home.html
...
<img src="{{ post.image.url}}" ..>
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
image = models.ImageField(upload_to="media/")
maybe,this setting is recommended debug-mode.
What shuld I change this setting.
Solution 1:[1]
As per the documentation:
This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL (e.g. http://media.example.com/).
With the helper function they mention being: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Setting up static & media files for nginx in production very simple, DigitalOcean has a great guide. The Static part is just a couple lines:
location /media/ {
root /home/sammy/myproject;
}
Solution 2:[2]
Set this code below to "urls.py" to show media files in "DEBUG = False":
# "urls.py"
from django.conf.urls import url
from django.views.static import serve
from django.conf import settings
urlpatterns = [
# ...
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | phoenix |
Solution 2 | Kai - Kazuya Ito |