How to run Django with Uvicorn webserver?

Viewed 5264

I have a Django project running on my local machine with dev server manage.py runserver and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed uvicorn and started the server, but as you can see below it fails to find Django static css files.

(envdev) user@lenovo:~/python/myproject$ uvicorn myproject.asgi:application --port 8001
Started server process [17426]

Waiting for application startup.
ASGI 'lifespan' protocol appears unsupported.
Application startup complete.
Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)

INFO:     127.0.0.1:45720 - "GET /admin/ HTTP/1.1" 200 OK
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/base.css
INFO:     127.0.0.1:45720 - "GET /static/admin/css/base.css HTTP/1.1" 404 Not Found
Not Found: /static/admin/css/dashboard.css
Not Found: /static/admin/css/dashboard.css
INFO:     127.0.0.1:45724 - "GET /static/admin/css/dashboard.css HTTP/1.1" 404 Not Found
Not Found: /static/admin/css/responsive.css
Not Found: /static/admin/css/responsive.css
INFO:     127.0.0.1:45726 - "GET /static/admin/css/responsive.css HTTP/1.1" 404 Not Found

Uvicorn has an option --root-path so I tried to specify the directory where these files are located but there is still the same error (path is correct). How can I solve this issue?

2 Answers

When not running with the built-in development server, you'll need to either

Add below code your settings.py file

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

Add below code in your urls.py

from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [.
.....] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Then run below command but static directory must exist

python manage.py collectstatic --noinput

start server

uvicorn main.asgi:application --host 0.0.0.0
Related