[Django]-Serving files uploaded by a user during development in django

5👍

django.contrib.staticfiles.views.serve() should not be used for deployment.

First, calling views.serve() anywhere will only work if DEBUG = True, and will raise an Http404 if used when DEBUG = 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 run collectstatic/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 the mimetype 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.

2👍

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?

👤jape

Leave a comment