Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static media during Django development: Why not MEDIA_ROOT?

Tags:

I read this guide about serving static media with Django during development.

I noticed that MEDIA_URL and MEDIA_ROOT were not used in this. Why? What's the difference?

I tried doing it with MEDIA_URL and MEDIA_ROOT, and got weird results.

like image 806
Ram Rachum Avatar asked Feb 10 '10 14:02

Ram Rachum


People also ask

Can Django serve static files in production?

During development, as long as you have DEBUG set to TRUE and you're using the staticfiles app, you can serve up static files using Django's development server. You don't even need to run the collecstatic command.

What is the difference between media and static files in Django?

Static files are meant for javascript/images etc, but media files are for user-uploaded content.

How do I serve media files in Django?

To make Django development server serve static we have to add a URL pattern in sitewide urls.py file. Now visit http://127.0.0.1:8000/media/python.png again, this time you should be able to see the image. Just as with static files, in the production, you should always use a real web server to serve media files.


1 Answers

In a production situation you will want your media to be served from your front end web server (Apache, Nginx or the like) to avoid extra load on the Django/Python process. The MEDIA_URL and MEDIA_ROOT are usually used for this.

Running the built in Development server you will need to set the correct url in your url.py file - I normally use something like this:

from django.conf import settings  urlpatterns += patterns('',     (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) 

Which picks up the MEDIA_ROOT from your settings file meaning that it works for development and live.

like image 153
Frozenskys Avatar answered Sep 23 '22 20:09

Frozenskys