如何在Django中通过Daphne 2.0托管静态媒体?Ubuntu部署静态文件加载失败求助
Hey there! I’ve been where you are—setting up Django with Daphne for the first time, watching the app run but all the CSS/JS/images failing to load. Let’s break down how to fix this, since Daphne isn’t built to handle static files efficiently out of the box.
First: Understand the Core Issue
Daphne is an ASGI server focused on handling WebSocket and async Django requests. It doesn’t have the optimized file-serving capabilities that WSGI servers (like Gunicorn) or dedicated web servers (like Nginx) have. So even if your STATIC_URL and MEDIA_URL are set correctly, Daphne won’t serve those files by default.
Option 1: Quick Fix for Development Environments
If you’re just testing and don’t want to set up a full reverse proxy yet, you can use WhiteNoise to serve static files directly through your ASGI app. Here’s how:
Install WhiteNoise:
pip install whitenoise[brotli]Update your
asgi.pyfile to wrap your Django application with WhiteNoise’s ASGI middleware:import os from django.core.asgi import get_asgi_application from whitenoise import WhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings') application = get_asgi_application() application = WhiteNoise(application, root='/path/to/your/static_root') # Add media files if needed application.add_files('/path/to/your/media_root', prefix='media/')Make sure your
settings.pyhas these values set correctly:STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Where collectstatic puts files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')Run
python manage.py collectstaticto gather all static files intoSTATIC_ROOT.
This works for development, but don’t use this in production—WhiteNoise is okay for small apps, but Nginx is far more efficient and secure.
Option 2: Production-Grade Fix with Nginx (Recommended)
For a production setup, you’ll want Nginx to handle all static/media file requests, and pass only dynamic/WebSocket requests to Daphne. Here’s a step-by-step guide:
Step 1: Configure Django Settings
First, confirm your static/media settings are correct (same as above), and run collectstatic to populate STATIC_ROOT.
Step 2: Set Up Nginx Configuration
Create or edit your Nginx site config (usually at /etc/nginx/sites-available/your_project):
server { listen 80; server_name your_domain_or_ip; # Serve static files directly location /static/ { alias /path/to/your/static_root/; expires 30d; add_header Cache-Control "public, max-age=2592000"; } # Serve media files directly location /media/ { alias /path/to/your/media_root/; expires 30d; add_header Cache-Control "public, max-age=2592000"; } # Pass all other requests to Daphne location / { proxy_pass http://127.0.0.1:8000; # Assuming Daphne is running on port 8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Handle WebSocket connections proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
Step 3: Enable the Site and Restart Nginx
- Create a symlink to enable the site:
sudo ln -s /etc/nginx/sites-available/your_project /etc/nginx/sites-enabled/ - Test Nginx config for errors:
sudo nginx -t - Restart Nginx:
sudo systemctl restart nginx
Step 4: Run Daphne
Make sure Daphne is running on the port you specified (8000 in the example):
daphne -b 127.0.0.1 -p 8000 your_project.asgi:application
For production, you’ll want to run Daphne as a service (using systemd) so it starts on boot.
Final Checks
- Double-check file permissions: Ensure Nginx has read access to your
STATIC_ROOTandMEDIA_ROOTdirectories. You can set permissions with:sudo chown -R www-data:www-data /path/to/your/static_root /path/to/your/media_root sudo chmod -R 755 /path/to/your/static_root /path/to/your/media_root - Clear your browser cache—sometimes old cached paths can cause issues even after fixing the config.
That should get your static and media files loading properly!
内容的提问来源于stack exchange,提问作者Darwin

