我正在将生成器对象results
从fx_rates
视图传递到这样的模板:
def fx_rates(request):
if request.method != 'POST':
form = FxForm()
results=[]
else:
form = FxForm(request.POST)
if form.is_valid():
scraper = FxScraper()
scraper.from_currencies.append(form.cleaned_data['from_currencies'])
scraper.dates = form.cleaned_data['dates'].split(" ")
scraper.to_currency = form.cleaned_data['to_currency']
results = scraper.results()
context = {'form':form, 'results':results}
return render(request, 'map_assistant/fx_rates.html',context)
在此视图的模板中,我使用以下显示结果:
<ul>
{% for result in results %}
<li>{{result}}</li>
{% endfor %}
</ul>
(猜测以下问题解决后,我可以将其更改为{{next(results)}}
)。
问题是,当使用GET方法调用视图时,我不知道如何防止显示“ []”。
我无法删除results=[]
行,因为使用GET调用视图时会出错。
猜猜方法为GET时,我需要从context
字典中删除结果吗?
答案 0 :(得分:0)
当方法为GET时,请尝试:
results = ""
这样,结果被赋予空值。
答案 1 :(得分:0)
您可以这样做
def fx_rates(request):
show_div = 'none'
if request.method != 'POST':
form = FxForm()
results=[]
else:
show_div = 'block'
form = FxForm(request.POST)
if form.is_valid():
scraper = FxScraper()
scraper.from_currencies.append(form.cleaned_data['from_currencies'])
scraper.dates = form.cleaned_data['dates'].split(" ")
scraper.to_currency = form.cleaned_data['to_currency']
results = scraper.results()
context = {'form':form, 'results':results, 'show_div':show_div}
return render(request, 'map_assistant/fx_rates.html',context)
您的html看起来像这样
<div style="display:{{show_div}}">
<ul>
{% for result in results %}
<li>{{result}}</li>
{% endfor %}
</ul>
</div>
或简单地检查
{% if result %}
<ul>
{% for result in results %}
<li>{{result}}</li>
{% endfor %}
</ul>
{% else %}
{% endif %}