Skip to main content

Serving Static Files in Production

In a previous chapter we introduced the concept of a static file, that is, a file whose content is not generated in real time by Django or any other Python code, unlike, for example, HTML templates, which are processed in each request. By default, when the web browser requests the content of a static file (e.g. /static/myapp/styles.css), Django looks for it in the file system, opens it, reads it, and returns it as the content of an HTTP response. This is fine during development, but in production it is better to let the web server (Apache, NGINX, or whatever it is configured) take care of it, which it will be able to do it faster and more efficiently. It is not only better, but necessary, since Django only serves static files when debug mode is enabled.

PythonAnywhere by default serves static files from the static folder of your project, as you can see in the Web tab:

Static Files in PythonAnywhere

According to this, your static files should be inside /home/<username>/myproject/static/, but they are actually stored in /home/<username>/myproject/myapp/static/ (that is, inside your application folder, not your project folder.) Django provides a command to automatically copy files from one directory to another in production, which you must execute whenever you make changes to any of your static files.

Before getting there, you must set up in your project configuration the path in which PythonAnywhere will be looking for static files. Open your project's settings.py, and you will find this line near the end of the file:

STATIC_URL = '/static/'

Below this line, add (do not replace!) the STATIC_ROOT variable with the path highlighted in the above image:

STATIC_ROOT = '/home/rpacc/myproject/static'

(Again, remember to replace "rpacc" with your PythonAnywhere username.)

Now go to the Files tab, navigate to the myproject/myproject/ folder and upload the updated version of settings.py. Then, go back to the parent folder (that is, /home/<username>/myproject/, where manage.py is located) and press the Open Bash console here button.

When the terminal has opened, execute the collectstatic command, which will copy static files from your application's static folder to your project's:

python3.10 manage.py collectstatic

(If you are using another version of Python, change "3.10" to the corresponding version.)

Since you made changes in settings.py, it is necessary to reload the application by going to the Web tab and pressing the Reload button. Once this is done, PythonAnywhere will be able to serve the static files of your project.