Krishna Krishna - 4 months ago 7
HTML Question

Expecting the text entered in the searchbox to be printed on the results page

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 %}


What i am trying to do is to first enter a question in the searchbox and then display it in the results page using django

Answer

In your view, results is a string, so {% for result in results %} will loop through each letter in the string, and {{ result.xxxx }} will not display anything because strings don't have an xxxx attribute.

I would replace that loop in the template with simply:

{{ results }}

You can simplify your view to use render instead of render_to_response. Since you have if query, you also have to set query in the else statement, otherwise you'll get a name error.

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,})

You might find the forms chapter from Mastering Django useful.

Comments