You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django媒体文件网站不显示求助:开发正常生产环境异常

Troubleshooting Uploaded Content Not Displaying in Production (Works in Dev)

Hey there, I’ve run into this exact scenario a few times—let’s break down the most likely fixes based on your details (static files work, uploads are in the right directory, frontend links look correct):

  • Verify web server media file serving configuration
    Unlike development environments, Django won’t automatically serve media files in production. Even if your MEDIA_ROOT and MEDIA_URL are set correctly in settings.py, you need to configure your web server (Nginx/Apache) to map the MEDIA_URL path to your actual media directory.
    For example, in Nginx, add this block to your server config:

    location /media/ {
        alias /absolute/path/to/your/media/root/;
        expires 30d;
    }
    

    Double-check that the alias path matches your MEDIA_ROOT exactly, including trailing slashes if needed.

  • Check file and directory permissions
    This is the #1 culprit I’ve seen. Even if files are saved to the correct folder, the web server process (e.g., www-data for Nginx/Apache) might not have read access to them.
    Run these commands to fix permissions:

    # Give ownership to the web server user
    sudo chown -R www-data:www-data /path/to/your/media/root
    # Ensure files are readable
    sudo chmod -R 644 /path/to/your/media/root
    # Ensure directories are accessible
    sudo chmod -R 755 /path/to/your/media/root
    
  • Rule out caching issues
    Sometimes the browser or a CDN (if you’re using one) caches an old, broken link. Try:

    • Forcing a hard refresh (Ctrl+F5 or Cmd+Shift+R)
    • Testing in an incognito window
    • Temporarily disabling CDN caching if you have it set up
  • Validate template link generation
    Make sure you’re using Django’s built-in URL generation for uploaded files instead of hardcoding paths. For example:

    # Correct way
    <img src="{{ user_uploaded_file.url }}" alt="Uploaded content">
    
    # Avoid hardcoding like this (breaks if MEDIA_URL changes)
    <img src="/media/{{ user_uploaded_file.name }}" alt="Uploaded content">
    

    Also confirm that the file object is properly passed to the template context.

  • Double-check DEBUG mode and MEDIA settings
    Even though static files work, confirm DEBUG = False in production (as it should be). Also verify that MEDIA_URL doesn’t have typos—for example, missing a trailing slash that your web server config expects.

内容的提问来源于stack exchange,提问作者Jason Howard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:37:36