views.py
from weatherbot.models import Question
from django.template import RequestContext
from django.shortcuts import render_to_response
def search(request):
query = request.GET.get('q')
if query:
results = query
context = RequestContext(request)
return render_to_response('results.html', {"results": results,}, context_instance=context)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^search/$', views.search, name = 'Ask for Weather Updates'),]
search.html
<form method="get" action="/search/">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
result.html
{% if results %}
{% for result in results %}
{{ result.xxxx }}
{% endfor %}
{% else %}
<h3 class='error'>Please enter a valid UID</h3>
<form method="get" action="//">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
{% endif %}
我要做的是首先在搜索框中输入一个问题,然后使用django将其显示在结果页面中
答案 0 :(得分:0)
在您看来,results
是一个字符串,因此{% for result in results %}
会遍历字符串中的每个字母,{{ result.xxxx }}
将不会显示任何内容,因为字符串不具有xxxx
属性。
我会简单地用模板替换那个循环:
{{ results }}
您可以简化视图,使用render
代替render_to_response
。由于您有if query
,因此您还必须在query
语句中设置else
,否则您将收到名称错误。
from django.shortcuts import render
def search(request):
query = request.GET.get('q')
if query:
results = query
else:
results = ''
return render_to_response(request, 'results.html', {"results": results,})
您可能会发现Mastering Django中的forms chapter很有用。