问题描述
使用Django Haystack设置搜索页面包括放入其URLconf片段 url(r'^ search /',include('haystack.urls'))。然而,这意味着(至少从我对Django / MVC的极其基础的了解),没有简单的方式来传递额外的上下文(即额外的字典键/值)来呈现到页面上。
特别是,我想自定义一个搜索字段来镜像从GET请求传递到页面上的变量:
< form method =getaction =。>
< input type =textname =qvalue =>
<! - result html here - >
< / form>
说参数?q = twitter 作为GET请求的一部分附加到URL;我想使值选择器等于 twitter 。如果我有控制权,我可能会这样做:
if request.method =='GET' :
q = request.GET ['q']
return render(request,'template.html',{'q':q})
pre>
然后使用 q 作为值的值选择器在HTML < input> 中。
有没有办法以简单的方式来完成这个除了编辑干草堆源之外吗?
解决方案使用自定义上下文处理器完成此操作:
$ b从django.template导入RequestContext
从django.http导入HttpResponse
def get_search_query(request)
search_query = request.GET.get('q','')
print search_query
return {
'search_query':search_query
}
然后,只需调用 {{search_query}} y的HTML模板。
Setting up a search page with Django Haystack involves putting in their URLconf snippet url(r'^search/', include('haystack.urls')). However, this means (at least from my extremely basic understanding of Django/MVC), that there is no simple way to pass extra context (i.e. an extra dictionary key/value) to be rendered onto the page.
In particular, I want to customize a search field to mirror the variable passed onto the page from a GET request:
<form method="get" action="."> <input type="text" name="q" value=""> <!-- result html here --> </form>
Say the parameter ?q=twitter is attached to the URL as part of a GET request; I'd like to make the value selector equal to twitter. If I had control of the view, I would likely do it something like this:
if request.method == 'GET': q = request.GET['q'] return render(request, 'template.html', {'q': q})
And then use q as the value for the value selector in the HTML <input>.
Is there any way to accomplish this in a simple manner, besides editing the Haystack source?
Accomplished this using a custom context processor:
from django.template import RequestContext from django.http import HttpResponse def get_search_query(request): search_query = request.GET.get('q', '') print search_query return { 'search_query':search_query }
Then, simply call {{ search_query }} in any of your HTML templates.
这篇关于将额外的上下文传递给Django Haystack模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!