javascript - 如何在Django python中添加Css和Js文件

标签 javascript html css django

我面临着在我的 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 传输:

最佳答案

  1. 这用于元素(公共(public))静态:

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
    
  2. 这是针对您的应用静态信息:

    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/

相关文章:

javascript - 如何使用 jquery 从 Sharepoint 用户配置文件数据库获取用户

javascript - 使用react-hook-form的Controller组件不允许自定义Antd Select显示标签

javascript - Jquery/Js 函数没有按预期工作

html - 屏幕在 bootstrap 4 上分成 3 部分

javascript - 如何仅将 css 应用于特定 div 中的链接?

jquery - 使用 css3 转换为鼠标移出添加不同的转换速度

javascript - 执行 'COUNT(id)' 查询后,无法从 RowDataPacket 访问 'SELECT COUNT'

javascript - 引用错误 : module is not defined - Karma/Jasmine configuration with Angular/Laravel app

jquery - 如何在 jquery 中单击时更改文本和正方形矩形?

jquery - 定位下拉菜单