[Answered ]-Django serving dynamic Files

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}}" />

Leave a comment