3

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.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
kue
  • 33
  • 1
  • 4
  • Did you run `python manage.py collectstatic`? https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/ – Marco Mar 17 '17 at 15:49
  • I would recommend to serve Media files not through the Django application, instead use a different vHost (with apache2, nginx, etc). Doing this gives you more control over the media files, and you can ensure that these files are served in a specific format (eg. text/plain or image/png) – Info-Screen Mar 17 '17 at 17:19

2 Answers2

6

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;
    }
phoenix
  • 7,988
  • 6
  • 39
  • 45
Jens Astrup
  • 2,415
  • 2
  • 14
  • 20
0

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}),
]
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129