【问题标题】:Static files not loading to django project静态文件未加载到 django 项目
【发布时间】:2022-01-12 08:13:50
【问题描述】:

我有一个项目,我的搭档在前端工作,没有使用任何框架,只使用了 js、html 和 css。我想使用 Django 将前面连接到后面。

这里是来自 settting.py 的设置

STATIC_ROOT = os.path.join('C:/Users/1224095/work/Backend/backend/static')

STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

我在我的 html 标头中添加了 {% load static %}。为了不让你感到困惑,我创建了一个名为 static 的静态目录,在里面我从前端获取了我的资产和插件,而且在每个地方,我都添加了 href= {% static 'path to the file' %}

结果,我收到 404 错误,有人知道为什么吗? 这是我的 html 示例:

<!doctype html>
<html lang="en">

{% load static %}

<head>

    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{% static 'assets/plugins/simplebar/css/simplebar.css' %}" rel="stylesheet" />
    <link href="{% static 'assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css' %}" rel="stylesheet" />
    <link href="{% static 'assets/plugins/metismenu/css/metisMenu.min.css' %}" rel="stylesheet" />
    <link href="{% static 'assets/plugins/vectormap/jquery-jvectormap-2.0.2.css' %}" rel="stylesheet" />
    <link href="{% static 'assets/plugins/highcharts/css/highcharts-white.css' %}" rel="stylesheet" />

【问题讨论】:

  • 在 settings.py 文件中设置 DEBUG=TRUE
  • 已经默认完成
  • 尝试用 STATIC_ROOT = 'C:/Users/1224095/work/Backend/backend/static' 改变第一行
  • 当页面加载一些 JS、CSS、Image 时,您在加载页面或在浏览器中的 DevTools 中得到 404 吗?

标签: javascript python css django


【解决方案1】:

(1): 你只能在你的 settting.py 中使用这个 -> STATIC_URL = '/static/'

(2):您必须将您的静态文件(JavaScript、CSS 等)复制并粘贴到您的templates

看起来像这样:

App
|_migrations
|_templates
|_static
    |__App (directory with the App name)
        |_assets
            |_js
            |_css
            |_img
            |_plugins
            |_....

您的 HTML 应该如下所示:

<!doctype html>
<html lang="en">

{% load static %}

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{% static 'App/assets/plugins/simplebar/css/simplebar.css' %}" rel="stylesheet" />

只是不要忘记在每个“资产”之前写 App

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-06-18
  • 2019-08-31
  • 2014-11-12
  • 2021-04-03
  • 2012-01-21
  • 2016-11-06
  • 1970-01-01
  • 2015-05-11
相关资源
最近更新 更多