Skip to main content
 首页 » 编程设计

python之静态媒体无法在 Django 中加载

2025年05月04日23webabcd

我的 settings.py包含以下配置参数。

STATIC_ROOT = '' 
 
STATIC_URL = '/static/' 
 
# Additional locations of static files 
STATICFILES_DIRS = ( 
    'C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows', 
) 

我项目的 CSS 文件位于 C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows/static/default.css .

我有一个应该提取 CSS 内容的模拟 HTML 文件,但 URL 是 404。

<link rel="stylesheet" href="{{ STATIC_URL }}static/default.css" />

我做错了什么?

请您参考如下方法:

要检查的事情:

  1. DEBUG = True 在 settings.py 中

  2. urls

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns 
     
    # ... the rest of your URLconf goes here ... 
     
    urlpatterns += staticfiles_urlpatterns() 
    
  3. 使用 context processor或 load static如果 {{ STATIC_URL }} 不工作

    If {{ STATIC_URL }} isn't working in your template, you're probably not using RequestContext when rendering the template.

    As a brief refresher, context processors add variables into the contexts of every template. However, context processors require that you use RequestContext when rendering templates. This happens automatically if you're using a generic view, but in views written by hand you'll need to explicitally use RequestContext To see how that works, and to read more details, check out Subclassing Context: RequestContext.