我正在开发一个使用 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/