Notes to self

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.

Work with me

I have some availability for contract work. I can be your fractional CTO, a Ruby on Rails engineer, or consultant. Write me at strzibny@strzibny.name.

RSS