Reputation: 2244
I'm fairly new to Django, and am working on a project where I use forms to get a user to enter a stock symbol and then using urllib I pull the data from Yahoo and return it. However, I'm not sure how to do this.
Here is my forms.py:
class Search(forms.Form):
search = forms.CharField()
Here is my views.py:
def search(request):
context = RequestContext(request)
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
success = True
subject = search.cleaned_data['search']
sourceCode = urllib2.urlopen("http://finance.yahoo.com/q/ks?s="+subject).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"search":search}, context)
This is the form I use to get users input (it has some bootstrap styling):
<form class="navbar-form navbar-right" role="search" action="/search/" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter stock symbol" name="search">
</div>
<button type="submit" value="Save" class="btn btn-primary">Submit</button>
</form>
And finally here is my search.html file where I'd like to display the data:
{% extends 'ui/base.html' %}
{% block title %} {{ search.search.value|upper }} {% endblock %}
{% block body_block %}
<div class="container">
<h2>{{ search.search.value|upper }}</h2>
<h2>{{ I'd like to display 'pbr' (as definied in my views.py) here }}</h2>
{% endif %}
</div>
{% endblock %}
What I's like to do is take the pbr from my views.py and display it in my templates. Anyone know if I can do this? Thanks.
Upvotes: 0
Views: 62
Reputation: 12092
Build a result
dictionary in your view as:
result = {}
if search.is_valid():
success = True
subject = search.cleaned_data['search']
sourceCode = urllib2.urlopen("http://finance.yahoo.com/q/ks?s="+subject).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
result['pbr'] = pbr
result['search'] = search
and return this result
as:
return render_to_response('ui/search.html', {"result":result}, context)
In your template now you can access the pbr
as:
<h2>{{ result.search.value|upper }}</h2>
<h2>{{ result.pbr }}</h2>
Upvotes: 1