使用Django在模板中显示视图变量?

时间:2014-05-23 16:47:54

标签: python django

我是Django的新手,我正在开发一个项目,我使用表单让用户输入股票代码,然后使用urllib从Yahoo中提取数据并将其返回。但是,我不知道该怎么做。

这是我的forms.py:

class Search(forms.Form):
    search = forms.CharField()

这是我的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)    

这是我用来获取用户输入的表单(它有一些引导样式):

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

最后这是我的search.html文件,我想显示数据:

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

我想做的是从我的views.py中获取pbr并将其显示在我的模板中。谁知道我能不能这样做?谢谢。

1 个答案:

答案 0 :(得分:1)

在您的视图中构建result字典:

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

并将此result作为:

返回
return render_to_response('ui/search.html', {"result":result},  context)

现在,您可以在模板中访问pbr

<h2>{{ result.search.value|upper }}</h2>
<h2>{{ result.pbr }}</h2>