【发布时间】:2020-01-26 21:19:10
【问题描述】:
我正在尝试创建一个网站,让访问者可以使用其他搜索引擎搜索书籍。我有一个接受查询的脚本,并返回一些带有搜索结果的 HTML,但我正在努力为此做一个前端。我正在使用 django,因为当我开始时它似乎是最好的选择,但现在我正在兜圈子,我无法弄清楚如何制作这个东西 - 我只是因为不同的教程和文档而不知所措在我能够让基本的东西工作之前,我阅读的所有内容都进入了高级内容。
我需要单独的搜索和结果模板吗?现在我收到错误The view book_search.views.search didn't return an HttpResponse object. It returned None instead.
我怎样才能修复这个错误和/或更好地设计整个事情?
这是我目前所拥有的(以 html 形式返回结果的脚本是 pull.py): 视图和网址来自 book_search 应用程序。
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from . import pull
from .forms import SearchForm
def index(request):
return HttpResponse("Welcome to the index page")
def test_search(request):
context = {'query': 'test query'}
return render(request, 'book_search/search.html', context)
def search(request):
if request.method == "GET":
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = pull.main(query)
context = {'query': query, 'form': form, 'results': results}
return render(request, 'book_search/results.html', context)
apps.py:
from django.apps import AppConfig
class BookSearchConfig(AppConfig):
name = 'book_search'
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('index', views.index, name='index'),
path('test', views.test_search, name='test_search'),
path('', views.search, name='search'),
]
forms.py:
class SearchForm(forms.Form):
query = forms.CharField(label='Search', max_length=200)
模板base.html:
<html>
<head>
</head>
<body>
<form method="GET" action="/search/">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% block content %}{% endblock %}
</body>
</html>
模板结果.html:
{% block content %}
{% results %}
{% endblock content %}
【问题讨论】:
-
当表单无效时感觉就像
searchreturn None,但由于格式化,它第一眼就被隐藏了。你能重新检查一下return render(request, 'book_search/results.html', context)是否真的和第一个if在同一个杠杆上吗? -
啊,我认为这可能是导致错误的原因。现在它给出的错误是“分配前引用的局部变量'上下文'”。调试页面说表单无效,所以这是有道理的。知道为什么它可能无效吗?