我正在尝试使用静态文件夹在本地设置 Django 站点。一切正常,只是我无法使 styles.css 和 mainlogo.png 文件正常工作。 styles.css 文件位于/static/css/styles.css,mainlogo.png 文件位于/static/img/mainlogo.png。下面的 base.html 文件位于 blog/templates/base.html 这是 base.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sentdex HTML5 and Django Tutorial</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="/static/css/styles.css" type = "text/css"/>
<meta name="viewport content = "width-device-width, initial-scale=1.0">
</head>
<body class="body">
<header class="mainHead">
<img src="/static/img/mainlogo.png" width="700" height="144">
<nav><ul>
<li><a href='/'>Home</a></li>
<li><a href='/blog/'>Blog</a></li>
<li><a href='/blog/latestnews/'>News</a></li>
<li><a href='/blog/latestnews/'>Archive</a></li>
</ul></nav>
</header>
<aside class="sideInfo">
<article>
<h3>Recent News</h3>
{% for post in object_list %}
<p>{{ post.date|date:"Y-m-d" }}<a href="/blog/{{post.id}}"> {{ post.title }}</a></p>
{% endfor %}
</article>
</aside>
{% block content %}
{% endblock %}
<footer class="mainFooter">
<p> copyright © 2013</p>
</footer>
</body>
</html>
我还尝试将 .css 文件和 .png 文件直接放入 base.html 所在的模板文件夹中,然后将 2 条相关行修改为:
<link rel="stylesheet" href="styles.css" type="text/css"/>
和
<img src="mainlogo.png" width="700" height="144">
我也试过将 http://放在 mainlogo.png 前面,但我仍然无法让图像或 styles.css 工作。
这些错误也出现在 cmd.exe 窗口中:
"GET /static/css/styles.css HTTP/1.1" 404 1646
"GET /static/img/mainlogo.png HTTP/1.1/" 404 1652
有什么想法吗?谢谢,汤姆
简单的 django 元素下载 .zip 位于此处:
最佳答案
我想你只是忘了添加这一行来获取静态文件:
<!DOCTYPE html>
{% load staticfiles %}
您正在使用开发服务器 (manage.py runserver
) DEBUG = True
时遇到这个问题,对吧?
因为 DEBUG = False
或在生产环境中,静态文件应该由您的服务器、CDN 或其他服务器提供:https://docs.djangoproject.com/en/1.6/howto/static-files/deployment/
如果这些都不起作用,请检查您的静态文件夹是否位于它应该位于的位置:https://docs.djangoproject.com/en/1.6/howto/static-files/ (在 INSTALLED_APPS 中正确配置 STATIC_ROOT 和 django.contrib.staticfiles 或在您的 ulrpatterns 中添加静态模式,如我提供的链接中的文档中所述)
关于css - Django 本地站点设置不适用于 styles.css 和 .png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975669/