我正在尝试读取dict以将值放入jinja2模板中:
answers = {'obs_18': None, 'obs_1': 'jack', 'rot3': None, 'obs_4': None, 'rot10': None, 'obs_8': None, 'rot7': None, 'rot6': None, 'rot13': None, 'rot21': None, 'obs_13': None, 'rot9': None, 'rot20': None, 'rot11': None, 'obs_7': None, 'rot17': None, 'obs_9': None, 'obs_21': None, 'obs_11': None, 'rot12': None, 'obs_19': None, 'obs_20': None, 'rot16': None, 'rot1': None, 'obs_10': None, 'rot15': None, 'rot18': None, '_id': ObjectId('5ad4b9a7f1ccd84582282207'), 'obs_16': None, 'obs_15': None, 'rot22': None, 'rot19': None, 'rot4': None, 'obs_5': None, 'rot5': None, 'obs_6': None, 'rot8': None, 'obs_12': None, 'obs_14': None, 'rot14': None, 'obs_17': None, 'rot2': None, 'obs_2': None, 'obs_22': None, 'obs_3': None}
使用loop.index将输入字段的默认值填入表单作为字符串,但显示的值只是字符串,如:
answers['obs_1']
,而不是正确的值' jack '。
我正在使用这个:
<input id="obs_{{ loop.index}}" name="obs_{{ loop.index }}" cols="30" rows="2" value="answers['obs_{{ loop.index }}']"></input>
如果我使用:
,则会显示这些值{{ answers }}
任何线索?
传递args:
@app.route('/checklist/<string:_id>', methods=['GET','POST'])
def checklist(_id):
form = CheckList()
perguntas = mongo.db.perguntas.find()
n_perguntas = mongo.db.perguntas.count()
print(n_perguntas)
perguntas.sort([('id',1)])
answers = mongo.db.checklists.find_one_or_404({'_id':ObjectId(_id)})
if request.method == 'POST':
for k in range(1,n_perguntas+1):
st = str(k)
answers.append({"rot"+st: request.form.get('rot'+st), "obs_"+st: request.form.get('obs_'+st)})
print(answers)
return render_template('checklist.html', form=form, perguntas=perguntas, answers=answers, logeduser=session['username'])
模板:
{% extends 'layout.html' %}
{% block content %}
<div class="col-md-12">
<h2 style="margin-top: 50px;"><i class="far fa-check-circle"></i> Check-list 912 {{ answers['_id']}} </h2>
<!-- <form action="/checklist" method="POST">
<div class="form-group">
{{ form.f1.label }} {{ form.f1(class="form-control form-control-md") }}
</div>
</form> -->
<form action="/checklist/{{ answers['_id']}}" role='form' method="POST">
<table class="table">
<tr>
<th>N.O.</th>
<th>Pergunta</th>
<th>Dispositivo</th>
<th>Resultado</th>
<th>Observação</th>
</tr>
{% for p in perguntas %}
<tr>
<td> {{ loop.index }} </td>
<td> {{ p.pergunta }} </td>
<td> {{ p.dispo }} </td>
<td>
<div class="radio">
<input name="rot{{loop.index}}" type="radio" value="1">Sim</input>
<br>
<input name="rot{{loop.index}}" type="radio" value="2">Não</input>
<br>
<input name="rot{{loop.index}}" type="radio" value="3">S/I</input>
</div>
</td>
<td>
<input id="obs_{{ loop.index}}" name="obs_{{ loop.index }}" value="answers['obs_{{ loop.index }}']"></input>
</td>
</tr>
{% endfor%}
</table>
<input class="btn btn-primary" type="submit" value="Enviar">
</form>
{{ answers }}
</div>
{% endblock %}
答案 0 :(得分:1)
作为参考,问题是在另一个变量中传递变量,因此,正确的方法是:
value={{ answers.get('obs_' + loop.index | string) }}