我的views.py
上有此方法:
def getExchangeRates(request):
""" Here we have the function that will retrieve the latest rates from fixer.io """
rates = []
response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd')
data = response.read()
rdata = json.loads(data.decode(), parse_float=float)
rates_from_rdata = rdata.get('rates', {})
for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']:
try:
rates.append(rates_from_rdata[rate_symbol])
except KeyError:
logging.warning('rate for {} not found in rdata'.format(rate_symbol))
pass
return render(request, 'index.html', rates)
这是我的模板(最初来自Flask应用程序):
{% block header %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div align="center" style="margin-top:35px;"><a href="/historical"><button type="button" class="btn btn-primary">Historical</button></a></div>
{% endblock %}
{% block body %}
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
<div id="chart_div" style="width: 900px; height: 500px;"><div>
<script type='text/javascript'>//<![CDATA[
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['Currency', 'Rate', { role: 'style' }],
['USD', {{rates[0]}}, 'gold'],
['GBP', {{rates[1]}}, 'silver'],
['HKD', {{rates[2]}}, 'brown'],
['AUD', {{rates[3]}}, 'blue'],
['SEK', {{rates[1]}}, 'red'],
['JPY', {{rates[2]}}, 'yellow'],
['NOK', {{rates[3]}}, 'orange'],
]);
var options = {
title: 'Exchange rate overview',
chartArea: {width: '50%'},
hAxis: {
title: '',
minValue: 0
},
vAxis: {
title: ''
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
//]]>
</script>
{% endblock %}
现在,它给我这样:
Internal Server Error: /
Traceback (most recent call last):
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kristian/user/user/fixerio/views.py", line 23, in getExchangeRates
return render(request, 'index.html', rates)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/loader.py", line 15, in get_template
return engine.get_template(template_name)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/backends/django.py", line 34, in get_template
return Template(self.engine.get_template(template_name), self)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/engine.py", line 144, in get_template
template, origin = self.find_template(template_name)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/engine.py", line 126, in find_template
template = loader.get_template(name, skip=skip)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/loaders/base.py", line 30, in get_template
contents, origin, origin.template_name, self.engine,
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 156, in __init__
self.nodelist = self.compile_nodelist()
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 194, in compile_nodelist
return parser.parse()
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 478, in parse
raise self.error(token, e)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 476, in parse
compiled_result = compile_func(self, token)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/loader_tags.py", line 209, in do_block
nodelist = parser.parse(('endblock',))
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 449, in parse
raise self.error(token, e)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 447, in parse
filter_expression = self.compile_filter(token.contents)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 563, in compile_filter
return FilterExpression(token, self)
File "/home/kristian/.virtualenvs/user/lib/python3.6/site-packages/django/template/base.py", line 663, in __init__
"from '%s'" % (token[upto:], token))
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]' from 'rates[0]'
视图上的当然线是这个
return render(request, 'index.html', rates)
我已经读到它可能与我尝试获取项目
{{rates[0]}}
的方式有关,再次在Flask上这可以正常工作,现在我只需要调整一些内容以使其与Django兼容即可。有任何想法吗?
最佳答案
这是语法问题。在Django模板中,我们不像python那样访问索引。我们使用点符号。所以,你必须
更改
{{rates[0]}}
至
{{rates.0}}
参考: