在 Django 中创建导航栏搜索框的最佳方法是什么?
我希望将一个搜索框集成到显示在每个页面顶部的导航栏中(嘿,在此 StackOverflow 页面顶部有一个我正在谈论的示例)。
也许 nav.html 可能看起来像:
<ul id="menu">
<li><a href="/products"></li>
<li><a href="/service"></li>
<li>{{ nav_search_form.as_p }}</li>
</ul>
也许 forms.py 可能包含:
class NavSearchForm(forms.Form):
query = forms.CharField(max_length=30, required=False)
根据 DRY 原则,我不希望views.py 在每个页面上寻找“查询”,例如:
def ProductsPage(request):
search_form = NavSearchForm()
if request.GET.has_key('query'):
query = request.GET['query'].strip()
# deal with 'Products' here...
def ServicePage(request):
search_form = NavSearchForm()
if request.GET.has_key('query'):
query = request.GET['query'].strip()
# deal with 'Service' here...
我已经并且可以轻松地编写一个页面,该页面将处理搜索查询并显示结果。如何最好地提取搜索词并将用户定向到该搜索页面(返回 HttpResponseRedirect('/results/?query=' + query))而不剥离每个页面上的 request.GET?
I would like to have a search box integrated into a nav bar that appears on the top of each page (hey, there is an example of what I am talking about up there at the top of this StackOverflow page).
Perhaps the nav.html may look like:
<ul id="menu">
<li><a href="/products"></li>
<li><a href="/service"></li>
<li>{{ nav_search_form.as_p }}</li>
</ul>
Perhaps forms.py may contain:
class NavSearchForm(forms.Form):
query = forms.CharField(max_length=30, required=False)
With the DRY principle I do not want views.py to be looking for a 'query' on every page like:
def ProductsPage(request):
search_form = NavSearchForm()
if request.GET.has_key('query'):
query = request.GET['query'].strip()
# deal with 'Products' here...
def ServicePage(request):
search_form = NavSearchForm()
if request.GET.has_key('query'):
query = request.GET['query'].strip()
# deal with 'Service' here...
I have and can easily program a page that will handle the search query and show results. How do you best extract the search terms and direct the user to that search page (return HttpResponseRedirect('/results/?query=' + query)) without stripping the request.GET on every page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需让搜索表单对您的常用搜索 URL 执行 GET 操作即可。
如果您不想硬连线 URL,请使用 URL 反向查找工具...
除非我误解了这个问题,否则听起来您可能认为表单必须获取/发布到加载当前页面的同一 URL。
Just have the search form do a GET on your common search URL.
Use the URL reverse lookup facility if you don't want to hardwire the URL...
Unless I misunderstood the question, it sounds like maybe you were thinking that forms have to get/post to the same URL that loaded the current page.
我们在其中一个网站上使用 Google CSE,它非常简单。您可以打开一些功能,但这很简单,并且您可以获得所有标准的 Google Goodness™。
We use a Google CSE on one of our sites and it's about as straightforward as you can get. There are a couple of features you can turn on, but it's trivial and you get all the standard Google Goodness™.
使用表单的力量
Use forms power