Search code examples
djangoweb-deploymentdjango-staticfilespythonanywhere

Django 1.11 - Static files not served - PythonAnywhere


I am deploying a django 1.11 app to a PythonAnywhere enviroment.

The settings file has 'django.contrib.staticfiles' added to the INSTALLED_APPS and the static config

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_col')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Folder structure of static folder:

├── css
├── fonts
├── img
├── jquery.templates
└── js
    └── jquery

When developing the app locally I was using "/static/jquery.templates/jquery.templates.js" without problems when doing manage.py runserver, but it doesn't work in deployment where I got no static files served whatsoever.

I executed manage.py collectstatic which worked without errors, but it moved the folder "jquery.templates" to js one:

static_col/
├── admin
    ...
├── css
├── fonts
├── img
└── js
    ├── jquery
    └── jquery.templates

Problem

The other static files are served, apparently, but the problem is that the link /static/js/jquery.templates/jquery.templates.js is not found. Obviously neither the /static/jquery.templates/jquery.templates.js link does not work. I have not idea how to approach this.

Serving static files is a pain with Django and I haven't found yet a working guide for this.

Thank you


Solution

  • I know I ran into similar issues deploying my first project. I found the solution was to place a folder in my apps static folder named the same as the app. This prevented a lot of odd name conflicts and unexpected locations for my static files.

    Structure of Application

    django_project
    ├─ static_col
    ├─ app1
    │  └─ static
    │     └─ app1
    │        ├─ js
    │        │  ├─ jquery1.js
    │        │  └─ functions1.js
    │        └─ css
    │           └─ styles1.css
    └─ app2
       └─ static
          └─ app2
             ├─ js
             │  └─ functions2.js
             └─ css
                └─ styles2.css
    

    After manage.py collectstatic

    django_project
    └─ static_col
       ├─ app1
       │  ├─ js
       │  │  ├─ jquery1.js
       │  │  └─ functions1.js
       │  └─ css
       │     └─ styles1.css
       └─ app2
          ├─ js
          │  └─ functions2.js
          └─ css
             └─ styles2.css
    

    Then in your template make sure you use {% static 'app1/js/functions1.js' %} (note the addition of app1) to reference your files. I found this corrected most problems with collectstatic.

    Finally, you need to make sure your server/host is actually serving the static files. You mentioned PythonAnywhere, so I would take a look at this blog post https://blog.pythonanywhere.com/60/ and double check that you have actually set up the proper directories to serve your static files (django_project/static_col in the above example).