Gunicorn returns "TypeError: expected str, bytes or os.PathLike object, not list" when testing Django site in Ubuntu server

Viewed 941

I am following this tutorial on DigitalOcean for the setup of a Django site. After initial setup and migrations, when I test the usual python manage.py runserver 0.0.0.0:8000 it works well (showing all images and grabbing all static files) with no errors.

When I test gunicorn --bind 0.0.0.0:8000 myproject.wsgi, no static files are grabbed (anyway, I understand that's Nginx's job) but this error appears for every static file requested in the page:

Internal Server Error: /static/img/logos/TSG-logo.png
Traceback (most recent call last):
  File "/home/tsg/buses/busesenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/tsg/buses/busesenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/tsg/buses/busesenv/lib/python3.8/site-packages/django/views/static.py", line 36, in serve
    fullpath = Path(safe_join(document_root, path))
  File "/home/tsg/buses/busesenv/lib/python3.8/site-packages/django/utils/_os.py", line 17, in safe_join
    final_path = abspath(join(base, *paths))
  File "/usr/lib/python3.8/posixpath.py", line 76, in join
    a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not list

I suspect this is related to settings.py, where STATICFILES_DIRS are declared as a list, according to Django:

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')

This doesn't look to me related to collectstatic (but it could be).

Why is it that there is no error in the Django server and when Gunicorn is used suddenly the list of paths is a problem?

I'm using Python 3.8.10, Django 3.2.5, gunicorn 20.1.0 and nginx 1.18.0 on Ubuntu 20.04.2 LTS.

1 Answers

Even though you have not posted full error traceback, yet i notice another issue in your code.

STATIC_ROOT and STATICFILE_DIRS should not be the same folder. By the way, i have you may notice i added staticfiles folder which will be automatically created when you run the collectstatic` commands.

Try this and let me know if it works

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Related