【问题标题】:Django URL from HTML search form来自 HTML 搜索表单的 Django URL
【发布时间】:2017-04-16 23:30:13
【问题描述】:

在我的模板中,我使用的是“搜索”类型的输入。执行操作时,它会返回页面“/search_results.html”。

我遇到的问题是将 /?search=yoursearch 附加到 URL 的末尾。

我的网址格式是

url(r'^search_results/(?P<search>\w+)/$, views.SearchView, name='search')

所以现在如果我输入 localhost:8000/search_results/apple,它将返回包含单词 apple 的结果。但是如果我使用搜索栏搜索苹果,它会返回 localhost:8000/search_results/?search=apple,这不是一个有效的 URL。我尝试使用

(?P<search>.*)

相反,但它说重定向太多。

有人知道如何在 Django 中使用搜索结果中的值吗?或者有没有办法安排我的网址,以便我可以解析等号后面的位?谢谢

【问题讨论】:

  • 这取决于您的视图是如何连接的。

标签: python html django


【解决方案1】:

不完全确定你的目标是什么,但我知道当匹配 urls django ignores 查询字符串(可以通过 request.META["QUERY_STRING"] 在请求对象中访问。这是一个小示例处理程序搜索。
urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^/search_results',views.search_handler)

views.py

def search_handler(request):
    query = {}
    for i in request.META["QUERY_STRING"].split("&"):
        query[i.split("=")[0]] = i.split("=")[1]
    search = query["search"]
    # your code here

【讨论】:

  • 谢谢,这似乎完全符合我的要求,而且非常简单!一个后续问题,在处理多词搜索时,它会在词之间添加一个 +。如果我搜索“test this”,搜索会得到值 test+this。我相信我可以通过在加号或其他地方拆分搜索来解决这个问题,但如果您有任何建议,那就太好了。
  • @Chris,我认为拆分可能是最好的方法。如果这对您有用,您能否将我的答案标记为正确?谢谢!
【解决方案2】:

在您的 html 表单中,您使用的是 get 方法还是 post 方法?

<form method="post">
</form>

【讨论】:

    【解决方案3】:

    在views.py中

    # no need to edit this
    def normalize_query(query_string,
                    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                    normspace=re.compile(r'\s{2,}').sub):
        ''' Splits the query string in invidual keywords, getting rid of 
            unecessary spaces and grouping quoted words together.
        '''
        return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
    
    
    # no need to edit this
    def get_query(query_string, search_fields):
        ''' Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields.'''
    
        query = None # Query to search for every search term
        terms = normalize_query(query_string)
    
        for term in terms:
            or_query = None # Query to search for a given term in each field
            for field_name in search_fields:
                q = Q(**{"%s__icontains" % field_name: term})
                if or_query is None:
                    or_query = q
                else:
                    or_query = or_query | q
            if query is None:
                query = or_query
            else:
                query = query & or_query
        return query
    

    要编辑的搜索视图

    def search(request):
        books = Mymodel.objects.all()
        query_string = ''
        found_entries = None
        source = ""
    
        # the 'search' in this request.GET is what appears in the url like
        #localhost:8000/?search=apple. 
        if ('search' in request.GET) and request.GET['search'].strip():
            query_string = request.GET['q']
            entry_query = get_query(query_string, [list, of, model, field, to, search])
        found_entries = Mymodel.objects.filter(entry_query)
    
        context = {
            'query_string': query_string,
            'found_entries': found_entries,
        }
    
        return render(request, 'pathto/search.html', context)
    

    现在在 urls.py 中你需要做的就是在 url 模式中添加这个

    url(
        regex=r'^search/$',
        view = search,
        name = 'search'
      ),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 2023-03-23
      • 2013-01-23
      • 2018-07-11
      相关资源
      最近更新 更多