我面临着在我的 django 元素中加载静态的 css 和 Javascript。 通过这段代码,图像文件正在加载,但只有 js 和 css 文件没有加载
{% load staticfiles %}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Home</title>
<link href="{% static "pro.css" %}" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="sd">
<h1>Hi my first django application</h1>
<img src="{% static "images/img08.jpg" %}"/>
<div id="demo"></div>
</div>
</body>
</html>
和我在浏览器中的页面源
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Home</title>
<link href="/static/pro.css rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="sd">
<h1></h1>
<img src="/static/images/img08.jpg"/>
<div id="demo"></div>
</div>
</body>
</html>
我的设置文件代码`
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS= (os.path.join(BASE_DIR,'questions','static','css'),os.path.join(BASE_DIR,'questions','static','js'),)
当我检查我的 Javascript 控制台时收到此错误消息 - 127.0.0.1/:19 资源解释为样式表但使用 MIME 类型 application/x-css 传输:
最佳答案
这用于元素(公共(public))静态:
STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
这是针对您的应用静态信息:
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', )
然后在模板中,您可以使用以下方式访问它:
{% load static %}
{# this is in project static dir == tip №1 == static/... #}
<script type="text/javascript" src="{% static ' js/bootstrap.min.js' %}"></script>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css">
{# suppose your app name is `questions` == tip №2 == questions/static/questions/... #}
<script type="text/javascript" src="{% static 'questions/js/some.js' %}"></script>
<link href="{% static 'questions/css/pro.css' %}" rel="stylesheet" type="text/css">
关于javascript - 如何在Django python中添加Css和Js文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164193/