首页 > 解决方案 > 如何在 django 框架中加载静态 JavaScript 文件

问题描述

我知道我做错了,在查阅了文档并观看了 3 个 YouTube 视频后,这些视频在前 7 分钟内旋转并复制它们仍然无法正常工作

我基本上是想通过点击一个按钮来打个招呼

我的 HTML 中的相关行

{% extends 'box2.html' %}
{% load static %}
{% block content %}
     <button class="btn btn-success mt-3" type="button" onclick="handle_do_thing_click()" type="">Add Planner</button>
{% endblock %}
{% block js_block %}
    <script type = "text/javascript/" src="{% static 'js/doThing.js' %}"></script>
{% endblock %}

我的 settings.py 静态设置

INSTALLED_APPS = ['django.contrib.staticfiles']

STATIC_URL = '/static/'

STATICFILES_DIRS = [BASE_DIR / 'static']

我的 url.py 文件

from django.urls import path
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [ these work
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

我存在于 app/static/js/doThing.js 中的 js 文件是 hello world

function handle_do_thing_click() {
    console.log("hello world");
}

控制台错误是 Uncaught ReferenceError: handle_do_thing_click is not defined at HTMLButtonElement.onclick

标签: javascriptdjangodjango-staticfiles

解决方案


对我来说,type="text/javascript/"<script>标签中删除使它起作用。


推荐阅读