Django static files on Zeit Now

The plan

  1. Set up a basic Django project
  2. Adjust your static files settings in Django
  3. Add a custom script for building static files on Now
  4. Update your Now config and deploy

1. Set up a basic Django project

There’s nothing special here, so if you have an existing project skip to #2.

$ mkdir now-django-staticfiles && cd now-django-staticfiles
$ pip install Django
$ django-admin startproject now_app .
$ python runserver
$ open http://localhost:8000
# requirements.txt
Django >=2

2. Adjust your static files settings

We’ll need to configure Django’s static settings so that we can collect all of our static files to a single directory and allow Now to deploy just that folder.

3. Add a staticfiles build script

Now’s @now/static-build builder allows us to run a custom bash script and deploy any files populated in a subdirectory of the build. This allows us to run python collectstatic in every build instead of having to run it before each deploy.

  1. yum install -y https://centos6... installs the IUS (“inline with upstream stable”) repository to make a Python 3.6 package available.
  2. yum install -y python36u installs Python 3.6
  3. curl https://bootstr... and python 3.6 install Pip for the new Python 3.6 installation.
  4. pip install -r requirements.txt installs any project requirements.
  5. python3.6 collectstatic finally collects staticfiles into the directory we configured in now_app/

4. Update/create a Now config and deploy

You’ll need to make two additions to your Now configuration to handle building and routing for static files. Update or create a now.json file in the project root to match the contents below:

  1. The builds section creates two separate builds: the first will run and then deploy the resulting files using the @now/static-build builder; the second will build a lambda against now_app/ using the @ardnt/now-python-wsgi builder.
  2. The routes section handles two routes patterns, in order: first it will match any requests to /static/... and pass those on to the static files directory, to be served by Now’s file serving systeml; second, it matches all other requests and passes them on your your application.
$ now

Further reading

For more on Zeit Now, check out the documentation, the GitHub organization, and the Spectrum group.



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store