Django give Error 500 for all static files like CSS and Images, when DEBUG is False

This is expected behavior. Django does not serve static files or media files in production. You should configure nginx, etc. to serve files.

As is specified in the Static file development view section of the documentation:

This view will only work if DEBUG is True.

That’s because this view is grossly inefficient and probably
insecure
. This is only intended for local development, and should
never be used in production
.

Normally you should configure nginx, apache web server to serve static files. These web servers are likely more efficient, and have more dedicated tooling for security.

Django offers some tooling to help you set up static files, for example with the collectstatic command [Django-doc] to collect static files in a single location. The documentation furthermore describes how to make a basic configuration for apache and nginx.

There is also a package whitenoise if you really want to let Django serve static files in production, but as said in the documentation:

Isn’t serving static files from Python horribly inefficient?

The short answer to this is that if you care about performance and
efficiency then you should be using WhiteNoise behind a CDN like
CloudFront. If you’re doing that then, because of the caching headers
WhiteNoise sends, the vast majority of static requests will be served
directly by the CDN without touching your application, so it really
doesn’t make much difference how efficient WhiteNoise is.

That said, WhiteNoise is pretty efficient. Because it only has to
serve a fixed set of files it does all the work of finding files and
determining the correct headers upfront on initialization. Requests
can then be served with little more than a dictionary lookup to find
the appropriate response. Also, when used with gunicorn (and most
other WSGI servers) the actual business of pushing the file down the
network interface is handled by the kernel’s very efficient sendfile
syscall, not by Python.

Leave a Comment