1

I have a problem about serving admin uploaded files in my templates.

I set:

MEDIA_URL='/media/'
MEDIA_ROOT = 'assets/'

and my models are like:

mainPhoto = models.ImageField(upload_to="articles/")

When in my templates, I try:

<img src="{{MEDIA_URL}}{{article.mainPhoto}}" />

The image doesn't show up on the website.

I found one deprecated solution with the django .serve(), but I hope to avoid using it.

I was looking everywhere and didn't find any answer, so I hope someone here will be able to help me.

Jamal
  • 763
  • 7
  • 22
  • 32
Edgarth
  • 13
  • 1
  • 6

1 Answers1

2

There are two parts to make this work. First is the Django configuration. There are really two settings for this which you have already mentioned - MEDIA_URL and MEDIA_ROOT. As already noted in the comments the MEDIA_ROOT has to be an absolute path. For example:

MEDIA_ROOT = `/abs/path/to/project/media/`

Second part is actually serving the files. If you are in production, you NEVER want to serve your static or media files through Django so you should configure Apache or nginx or whatever server system you are using to serve the files instead of Django. If you are on the other hand still developing the app, there is a simple way to make Django serve media files. The idea is to modify your urls.py and use the Django's static files server to serve media files as well:

# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
    # other patterns
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

More about this approach at Django docs.

Also FYI, you probably should not use {{MEDIA_URL}}{{article.mainPhoto}} to get the url of an image. This approach will break for example if you will no longer use file system storage for static files and will switch to something different like Amazon S3. It is always a good idea for the storage backend to figure out the url:

<img src="{{article.mainPhoto.url}}" />
miki725
  • 27,207
  • 17
  • 105
  • 121
  • 3
    Okay thank you, I didn't configure well the nginx server and your: {{article.mainPhoto.url}} solved another problem. I'm waiting the day I will be better at django programming and help people too ^^. – Edgarth Sep 30 '13 at 16:50