我知道 SO 上有很多类似的线程实际上有相同的问题 - 但我无法解决我的问题
Django 版本
>>> import django
>>> print django.get_version()
1.6.2
我想从模板访问静态文件(css、图像等)。
<link rel="stylesheet" type="text/css" href="styles.css" />
我的文件夹结构
Project
|-- Project
|-- settings.py
|-- ...
|-- app
|-- views.py
|-- ...
|-- templates
|-- a_template.html
|-- static
|-- styles.css
settings.py(重要部分)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'server',
)
STATIC_URL = '/static/'
我为 STATIC_URL 尝试了很多不同的解决方案(甚至是绝对路径),但没有一个对我有用。
请您参考如下方法:
首先,我将通过添加到模板顶部来使用 static 模板标签:
{% load static %}
然后,在 href 中:
href="{% static "styles.css" %}"
然后,我将更改我的 urls.py 并为您的开发服务器添加服务静态文件的可能性:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
/* you url patterns here */
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
这应该可以解决问题......
