Django 1.9 中的自定义搜索查询; GET 请求
Custom Search Query in Django 1.9; GET requests
我一直在尝试为一个博客项目实现一个搜索功能,现在各种教程中的几个不同实现都始终出现 404,无论输入如何,我正在寻找答案,这里。
这是对我来说最基本的,当然在 views.py
中:
def search(request):
try:
q = request.GET['q']
posts = Post.objects.filter(title__search=q)
return render_to_response('blog/search_post_list.html', {'object_list': posts, 'q':q})
except KeyError:
return render_to_response('blog/search_post_list.html')
在blog/urls.py
中:
url(r'^search', 搜索, 名称='search'),
/templates/blog/search_post_list.html
处有一个模板,其中包含一些包含 {% for post in object_list %}
的代码,与工作模板相同。
因此,转到任何 localhost:8000/blog/search?q=<search_query_here>
都是带有 404 的 Django 调试页面。
我将代码保持简单的原因是因为我觉得代码之外可能还有其他东西,我希望有人能告诉我在哪里可以找到它的代码。
编辑:
这是 404 页面:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/blog/search?q=what
Raised by: django.views.generic.detail.DetailView
No post found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
这是我的 DetailView 的 URL,因为它显然已被调用。
url(r'^(?P<slug>[a-zA-Z0-9-]+)/?$',
DetailView.as_view(
model=Post,
)),
尝试以这种方式添加 url-模式:
url(r'search/',
DetailView.as_view(
model=Post,
)),
(或'blog/search/')
使用 GET 请求参数将添加像 ***/search/?parameter_name1=value1¶meter_name2=value2
url /blog/search/
正在由您的详细信息视图而不是搜索视图处理。然后你得到一个 404,因为没有 post 和 slug=search
。
您可以通过将搜索 url 模式移动到详细信息模式上方来解决此问题。
我一直在尝试为一个博客项目实现一个搜索功能,现在各种教程中的几个不同实现都始终出现 404,无论输入如何,我正在寻找答案,这里。
这是对我来说最基本的,当然在 views.py
中:
def search(request):
try:
q = request.GET['q']
posts = Post.objects.filter(title__search=q)
return render_to_response('blog/search_post_list.html', {'object_list': posts, 'q':q})
except KeyError:
return render_to_response('blog/search_post_list.html')
在blog/urls.py
中:
url(r'^search', 搜索, 名称='search'),
/templates/blog/search_post_list.html
处有一个模板,其中包含一些包含 {% for post in object_list %}
的代码,与工作模板相同。
因此,转到任何 localhost:8000/blog/search?q=<search_query_here>
都是带有 404 的 Django 调试页面。
我将代码保持简单的原因是因为我觉得代码之外可能还有其他东西,我希望有人能告诉我在哪里可以找到它的代码。
编辑: 这是 404 页面:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/blog/search?q=what
Raised by: django.views.generic.detail.DetailView
No post found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
这是我的 DetailView 的 URL,因为它显然已被调用。
url(r'^(?P<slug>[a-zA-Z0-9-]+)/?$',
DetailView.as_view(
model=Post,
)),
尝试以这种方式添加 url-模式:
url(r'search/',
DetailView.as_view(
model=Post,
)),
(或'blog/search/') 使用 GET 请求参数将添加像 ***/search/?parameter_name1=value1¶meter_name2=value2
url /blog/search/
正在由您的详细信息视图而不是搜索视图处理。然后你得到一个 404,因为没有 post 和 slug=search
。
您可以通过将搜索 url 模式移动到详细信息模式上方来解决此问题。