首页 > 解决方案 > DJango React 未找到

问题描述

我是 DJango 和 React 的新手。我在 Pycharm 中创建了一个 DJango 项目,然后使用npm create-react-app frontend. 我在文件夹“src”中添加了一些 JavaScript 文件并编辑了一个自动创建的 index.css。我构建了 React 应用程序,然后启动了 DJango 服务器。控制台打印:

Not Found: /src/index.css
Not Found: /src/seigaiha.js
[25/Dec/2020 14:23:31] "GET /src/index.css HTTP/1.1" 404 2201
[25/Dec/2020 14:23:31] "GET /src/seigaiha.js HTTP/1.1" 404 2207

但是 .css 文件在已启动的站点上是可见的。.js 不是。

在文件夹中订购:

- frontend/
- - build/
- - - static/
- - - - css/ #here .css file after build has the same structure as index.css, so it buil
- - - - js/
- - - - media/
- - node-modules/
- - public/
- - src/
- - - index.css
- - - seigaiha.js

在 settings.py 中:

'DIRS': [
            os.path.join(BASE_DIR / 'frontend/build')
        ]

public/index.html

***some code***
<link rel="stylesheet" type="text/css" href="./src/index.css">
***some code***
<div class="pattern">
    <canvas id="canvas">Canvas not supported.</canvas>
    <script src="src/seigaiha.js"></script>
</div>
***some code***

我做错了什么?也许我需要将这些文件放在另一个文件夹中?或者可能路径是错误的?.js 文件名?当我只有 .html、.css 和 js 文件(没有反应)时,一切正常。

UPD:我在 stackoverflow 中阅读了一些建议,并使用npm start了 instesd 的命令npm run build。它没有用。

标签: javascriptpythoncssreactjsdjango

解决方案


尝试这样的事情:

FRONTEND_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "front-end"))

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(FRONTEND_DIR, "build")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

STATICFILES_DIRS = (os.path.join(FRONTEND_DIR, "build", "static"),)

推荐阅读