如何在django中创建URL并捕获搜索页面的输入?

时间:2015-05-29 16:26:19

标签: python django search

Django和编程新手。

我想创建一个搜索页面,目前有以下内容。

我的urlpatterns将其作为其中一种模式。

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

我的观点有一个功能

def search(request):
    if request.GET.get('q'):
        message = 'You submitted: %r' % request.GET['q']
    else:
        message = 'You submitted nothing!'
    return render(request, 'myapp/search.html', {'message': message})

search.html已

<!DOCTYPE html>
    <html>
      <head>
        <title>Search</title>
          </head>

       <body>
       <h1> Search </h1>

      <form action="/search/"  method="get" >
      <input type="text" name = "q">
      <input type="submit"value="Search"/>
    </form>
   </body>
 </html>

我的问题是当我去“myapp / search”时,我看到了搜索框,我在django调试工具栏中看到“views.search”功能已被捕获,但是当我在搜索框中输入文本并点击“搜索”时“我收到”当前网址,搜索/,与其中任何一个都不匹配。“加上django调试工具栏只显示一个GET变量捕获,但在Views中没有任何内容。

1)因此,在点击“搜索”按钮后,如何关联“views.search”。

2)在我的网址模式中,我是否需要另一个网址模式,如果是这样,应该是什么?

由于

1 个答案:

答案 0 :(得分:0)

您自己说URL是“/ myapp / search /”,但表单的“action”参数 - 确定表单数据的发送位置 - 只是“/ search /”。您需要使其相同,以便将数据发送到该URL。

最好的方法是使用{% url %}标记:

<form action="{% url "search" %}"  method="get">