This might be a dumb question but in the documentation it says:
Serving files uploaded by a user during development.¶
During development, you can serve user-uploaded media files from MEDIA_ROOT using the
django.contrib.staticfiles.views.serve()
view.This is not suitable for production use! For some common deployment strategies, see Deploying static files.
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Does that mean for production use + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
should not be used or should be used?
The way I understood this is that you shouldn't use django.contrib.staticfiles.views.serve()
but I'm not sure if that's not the same
django.contrib.staticfiles.views.serve()
should not be used for deployment.First, calling
views.serve()
anywhere will only work ifDEBUG = True
, and will raise anHttp404
if used whenDEBUG = False
, as should be the case when your app is deployed. The benefit of using this in development, however, is such that you don't have to runcollectstatic
/gather your static files: you can pull them from your static or media root without having to move things around.It's also somewhat insecure:
views.serve()
will guess the content type of the the file its serving using themimetype
module, which will rely on the map files for the platform you're developing on: the behavior might not be the same in production because of the mimetype module in your specific environment.The docs have more on
django.contrib.staticfiles.views.serve()
.Now when it comes to production, serving static/media files isn't something that Django's WSGI will do well for you. Django is written to serve application content, and won't perform as well when it comes to serving static/user uploaded content. If you're expecting even medium load, using a separate server such as Apache or Nginx in conjunction with a web server like uWSGI is far more sustainable and can handle more. This doc details more on how to set those up/explains more.
In production, you should have
Debug = False
. When you do that, static files are no longer served by Django.A popular substitute is using Amazon's S3 Buckets. For example purposes, let's say you create a new bucket. Your
MEDIA_URL
would look something like:MEDIA_URL = 'bucket.s3.amazonaws.com/media'
You would serve static files the same way.
Does that answer your question?