我正在开发一个Python-Flask Web应用程序,它应该可以作为政治家的维基百科。当我创建一个新的政治家时,它被默认为草稿,可以被更高级别的成员接受。因此,当我创建政治家页面时,它被检查作为草稿,当管理员接受该草稿时,草稿值将转到 false 。 我想知道如何根据属性草稿的列值勾选/取消勾选复选框,这是布尔(True / False)。然后我想根据表单结果更改它。这是一个编辑功能,你会看到:
这是我的政治家表格,我用来编辑的表格:
class PoliticForm(FlaskForm):
publicName = StringField('Public Name', validators=[DataRequired("Please enter politician public name.")])
completeName = StringField('Complete Name', validators=[DataRequired("Please enter politician complete name.")])
startDate = DateField('Start Date', format='%m-%d-%Y', validators=[DataRequired("Please enter the politician start Date.")])
endDate = DateField('End Date', format='%m-%d-%Y', validators=(validators.Optional(),))
draft = RadioField('Draft', choices=[(True,'Yes'),(False,'No')], )
submit = SubmitField('Add Politician', validators=(validators.Optional(),))
我想检查 HTML Jinja2 视图中的草稿行,即:
<div class="form-group">
<label for="draft">Draft</label>
<input type="checkbox" name="draft" class="form-control" id="email" value="{{politician.draft}}">
</div>
我是否需要使用已检查参数?如何选中 True 并取消选中 False ,然后将该更改发送给我的控制器?
政治家/ views.py / edit_politician
@politicians_blueprint.route("/edit_politician/<idPol>", methods=["POST", "GET"])
@login_required
def edit_politician(idPol=1):
form = PoliticForm()
politician = Politic.query.filter_by(idPolitician=idPol).first()
if request.method == "POST":
politician.publicName = request.form['publicName']
politician.completeName = request.form['completeName']
politician.draft = request.form['draft']
if request.form.get('date') != 'None':
politician.startDate = datetime.datetime.strptime(request.form.get('date'), '%m/%d/%Y').strftime('%Y-%m-%d')
print politician.startDate
if request.form.get('date2') != 'None':
politician.endDate = datetime.datetime.strptime(request.form.get('date2'), '%m/%d/%Y').strftime('%Y-%m-%d')
print politician.endDate
db.session.commit()
return redirect(url_for('home.home'))
elif request.method == "GET":
print politician.startDate
if politician.startDate is not None:
dateStart = politician.startDate.strftime("%Y-%m-%d")
politician.startDate = datetime.datetime.strptime(dateStart, '%Y-%m-%d').strftime('%m/%d/%Y')
if politician.endDate is not None:
dateEnd = politician.endDate.strftime("%Y-%m-%d")
politician.endDate = datetime.datetime.strptime(dateEnd, '%Y-%m-%d').strftime('%m/%d/%Y')
return render_template("editPolitician.html", politician=politician)
有什么想法吗?我真的很挣扎......
此致
答案 0 :(得分:0)
您可以尝试类似
的内容<input type="checkbox" name="draft" class="form-control" id="email" {% if politician.draft %}checked="checked"{% endif %}>
或者通过jQuery修改复选框的状态(如果你使用它)
<script>
{% if politician.draft %}
$('input[name="draft"]').prop('checked', true);
{% endif %}
</script>