【问题标题】:Django React page can't load css filesDjango React 页面无法加载 css 文件
【发布时间】:2020-10-21 08:14:36
【问题描述】:

我正在使用 djangorest 框架创建一个应用程序 用于后端,React 用于前端。后端和前端都是同一个 django 项目的应用程序。但是,在托管我的网站时,CSS 文件没有加载,很可能是因为路径。

我的frontend django 应用中的目录结构如下:

$ tree -d -L 1
.
├── migrations
├── node_modules
├── __pycache__
├── src
├── static
└── templates

模板目录如下所示:

templates/
└── frontend
    ├── css
    │   ├── bootstrap.css
    │   ├── bootstrap.css.map
    │   ├── bootstrap.min.css
    │   ├── bootstrap-theme.css
    │   ├── bootstrap-theme.css.map
    │   ├── bootstrap-theme.min.css
    │   ├── fontAwesome.css
    │   ├── fonts
    │   │   ├── flexslider-icon.eot
    │   │   ├── flexslider-icon.svg
    │   │   ├── flexslider-icon.ttf
    │   │   └── flexslider-icon.woff
    │   ├── light-box.css
    │   ├── owl-carousel.css
    │   └── templatemo-style.css
    └── index.html

我的index.html 文件如下所示:

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>abcd</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="/frontend/css/fontAwesome.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">

        <script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
    </head>
<body>
<div id="app">
    <!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>

我在托管网站时遇到了以下日志:

[30/Jun/2020 22:39:59] "GET / HTTP/1.1" 200 1154
Not Found: /css/bootstrap.min.css
[30/Jun/2020 22:39:59] "GET /css/bootstrap.min.css HTTP/1.1" 404 2313
Not Found: /css/fontAwesome.css
[30/Jun/2020 22:39:59] "GET /css/fontAwesome.css HTTP/1.1" 404 2307
[30/Jun/2020 22:39:59] "GET /static/frontend/main.js HTTP/1.1" 200 1004248
[30/Jun/2020 22:40:00] "GET /api/event HTTP/1.1" 301 0

我不确定如何设置 css 文件的路径,以及它们是否应该在我放入的目录中。如果我的 react 应用程序是我项目中的 django 应用程序,那么正确的目录结构是什么?

【问题讨论】:

    标签: javascript html reactjs django-rest-framework


    【解决方案1】:

    您的css 文件夹不应该在您的templates 文件夹中,它应该在您的static 文件夹中。只有这个文件夹会暴露给外界。模板文件夹只是 django 获取其模板以将其呈现给客户端的地方,但它并不直接暴露它。

    同时不要忘记运行python manage.py collectstatic

    【讨论】:

    • 这些文件夹在哪里配置?因为我自己在我的情况下创建了它们
    • 当前运行 collectstatic 命令,将我的 CSS 文件复制到我的项目(前端上一层)目录中的静态文件夹中。但是,CSS 文件仍未加载
    猜你喜欢
    • 2019-11-11
    • 2021-09-05
    • 2011-04-17
    • 2011-11-26
    • 2013-07-28
    • 2013-02-28
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多