Serve Django static assets with Gunicorn

Serving static assets by the application server such as Gunicorn is usually not a good idea. We should prefer a web server with a better performance, but what if you want to serve the assets directly with the Django application?

In case you want to do that, either for testing or for avoiding NGINX process in your application Docker container, you can do so by including the static files URLs returned by staticfiles_urlpatterns() in urlpatterns variable in your urls.py.

Like this:

--- a/mysite/urls.py
+++ b/mysite/urls.py
@@ -15,8 +15,11 @@ Including another URLconf
 """
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 from django.urls import include, path

 urlpatterns = [
     path('polls/', include('polls.urls')),
     path('admin/', admin.site.urls),
 ]
+
+urlpatterns += staticfiles_urlpatterns()

With this change, your Python application server will serve static assets as well.

← BUY THE PRE-RELEASE

I am writing a complete guide on web application deployment. Ruby with Puma, Python with Gunicorn, NGINX, PostgreSQL, Redis, networking, processes, systemd, backups, and all your usual suspects. 19 chapters and 2 case studies already available.

More →