1

I have a model where there is a ImageField but in the template doesn't appears. The upload of the image is OK (in media_root/one/image.jpg)

Settings.py:

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

Urls.py

(...)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

Models.py

class myModel1(models.Model):
__(...)
__image = models.ImageField(upload_to='one', default="")
__(...)

And on my template, I make this:

 <img src="{{ myModel1.image.url }}" alt="{{ myModel1.name }} image" />

And on the HTML is like:

 (...)**src="/media/one/photo_p33Mo8a.jpg"**(...)

But the image is not displayed

error 404 not found:

 GET http://localhost:8000/media/one/photo_p33Mo8a.jpg 404 (NOT FOUND)

Can someone help me?

PD: Sorry, my first time writing on stackOverFlow.

Have to comment that in the media_root/one/ there appears the image, but the folder /media/ is still empty.

FOLDER STRUCTURE: Proyect:
___app_folder
________media
________models.py....
___media_root
________one
____________image.jpg
___mainFolder(settings,urls..)
___static_root(...)

1 Answers1

1

Try in your tremplate:

<img src="{{ MEDIA_URL }}{{ myModel1.image }}" alt="{{ myModel1.name }} image" />

*EDIT

It seems you have to add in your urls.py file:

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

# ... the rest of your URLconf goes here ...

if settings.DEBUG:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
   ]

Edit2

Your ROOT_MEDIA path should be:

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_root")
doru
  • 9,022
  • 2
  • 33
  • 43
  • Nope :S. Now it creates another directory: Before: media_root/one/image.jpg and now media_root/one/one/image.jpg. And didnt work :( – Karramarro Gorri Dec 06 '15 at 15:21
  • Yes I did. The strange thing is that in the HTML img src appears '/media/one/image.jpg' but cant find it :S – Karramarro Gorri Dec 06 '15 at 15:33
  • I did it. But I see that {{ MEDIA_URL }} in the img tag doesn't change anything. In the HTML I see the same with or without {{ MEDIA_URL }}. I see: one/image.jpg – Karramarro Gorri Dec 06 '15 at 15:47
  • Worked. Thanks very much. Whitch was my main error? I was adding the information on my app/urls.py file, and not in my project/urls.py file. o.0'... In the template worked like this:. THX very much. – Karramarro Gorri Dec 06 '15 at 16:07