我正在与PostgreSQL数据库一起工作的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
),并在我的html正文中包含<script src="item_search.js"></script>
。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服务器,则需要设置staticfiles。
然后,您可以在模板中将静态位置称为
{% 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/