来自HTML搜索表单的Django URL

时间:2017-04-16 23:30:14

标签: python html django

在我的模板中,我使用的输入类型为"搜索"。执行操作时,它将返回页面" /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中使用搜索结果中的值?或者有没有办法安排我的URL,以便我可以在等号后解析位?感谢

3 个答案:

答案 0 :(得分:1)

不完全确定你的目标是什么,但我知道匹配网址时django 忽略查询字符串(可以通过request.META["QUERY_STRING"]在请求对象中访问。这里&#39;搜索的一个小例子处理程序 的 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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

在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'
  ),