javascript - 外部 javascript/jquery 未加载到 django 项目内部

标签 javascript jquery python html django

我正在开发一个使用 postgres 数据库的 django 项目。

我有一个搜索表单,允许用户搜索数据库。搜索表单工作得很好。我想通过使用 javascript 和 jquery 向表单添加自动完成功能来使其更加用户友好。

如果我将 jquery 包含在我的 html 文档正文中,则一切正常。
示例search.html (无关部分省略):

<html>
<head>
<title>Search</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
</head>

<body>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
  <script>
  $(function() {
    var availStations = 
        ['red', 'blue', 'green', 'purple', 'pink', 'black'];

    $(".stations").autocomplete({
        source: availStations
    });
});
</script>
<br>
<form action = "/search/" method = "get">
<div class = "ui-widget">
<label for="stations">Search for: </label>
    <input type = "text" name ="q" class="stations">

[....]

我想将其移至外部文件 ( item_search.js ) 并包含 <script src="item_search.js"></script>在我的 html 正文中。

item_search.js看起来像这样:

  $(function() {
    var availStations = 
        ['red', 'blue', 'green', 'purple', 'pink', 'black'];

    $(".stations").autocomplete({
        source: availStations
    });
});

当我这样做并打开search.html时直接归档一切正常。但是如果我通过运行 python manage.py runserver 打开它jquery 自动完成功能不起作用 我的控制台显示以下消息:

Failed to load resource: the server responded with a status of 404 (NOT FOUND) http://127.0.0.1:8000/search-form/item_search.js

显然当我打开search.html时直接它根本不与 django 项目连接,因此搜索实际上不起作用,但至少自动完成可以。可能发生什么事情??

最佳答案

如果你想使用内置的 django 服务器,你将需要设置静态文件。 然后在您的模板中,您可以将静态位置引用为

{% load static from staticfiles  %}
<html>
...
<script src="{% static "item_search.js" %}"></script>

这假设您已将 item_search.js 放入 STATIC_ROOT 中。 另外,不要忘记在每次修改文件后运行collectstatic。

关于javascript - 外部 javascript/jquery 未加载到 django 项目内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17537827/

相关文章:

javascript - 获取网页上使用 TAB 按钮选择的项目的标题

python 3 : maximum recursion depth exceeded while getting the __repr__ of a list

python - Django 。如何在模板中使用 for 循环在一行中显示对象列表?

javascript - 复制文本区域动画功能

javascript - 如何重播鼠标坐标列表以反射(reflect)输入它们的节奏?

javascript - 如何检查一个对象是否作为属性嵌套在另一个对象的属性中?

python - 如何在 Python 中将 Azure Blob 文件 CSV 转换为 Excel

javascript - Jquery:如何用文本框值显示日期?

javascript - 使用 jquery 进行 Onsubmit URL 重定向

php - 通过 VPN 剥离请求数据的 AJAX Post 请求