【问题标题】:Custom Search Query in Django 1.9; GET requestsDjango 1.9 中的自定义搜索查询;获取请求
【发布时间】:2016-04-05 21:59:47
【问题描述】:

我一直在尝试为博客项目实现搜索功能,现在各种教程中的几种不同实现都一致地出现 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, name='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,
    )),

【问题讨论】:

  • 404调试页面的全文是什么?
  • @Alasdair 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。添加。

标签: python django sqlite querying


【解决方案1】:

url /blog/search/ 正在由您的详细视图而不是搜索视图处理。然后你会得到一个 404,因为没有 slug=search 的帖子。

您可以通过将搜索 url 模式移动到详细信息模式上方来解决此问题。

【讨论】:

  • 我仍然收到一个错误:NotImplementedError at /blog/search Full-text search is not implemented for this database backend 甚至不确定这意味着什么。 sqlite3 问题?
  • 这是一个完全不同的问题。正如错误所说,您不能使用__search,因为 sqlite3 后端不支持它。你可以改用Post.objects.filter(title__contains=q)
  • 谢谢。你知道一个很好的资源来学习不同数据库支持的查询类型的一般图片吗?此外,我尝试使用不同的查询来执行posts +=,希望结果可能是一个有序列表,其中某些字段的位置高于其他字段,但不支持该操作。所以,我希望该资源将包含有助于此的信息。
  • The docs 应该说明一个方法是否只被某些后端支持。在您的代码中,posts 是一个查询集,因此您无法向其中添加项目。您可以先将其转换为列表,使用posts = lists(posts)
【解决方案2】:

尝试以这种方式添加 url-pattern:

url(r'search/',
    DetailView.as_view(
    model=Post,
    )),

(或“博客/搜索/”) 使用 GET 请求参数将添加类似 ***/search/?parameter_name1=value1&parameter_name2=value2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多