我需要在同一个模板上使用不同的表单名称指向两个视图,我使用该代码进行测试,但是它不起作用:
@home.route('/blogs/Article/<int:id>/<string:url_path>', methods=['GET'])
def show_article(id, url_path):
add_article = False
blog = Article.query.get_or_404(id)
form = ArticleForm(obj=blog)
if form.validate_on_submit():
blog.titre = form.titre.data
blog.url_path = form.url_path.data
blog.writ_by = form.writ_by.data
blog.body = form.body.data
blog.date_creation = form.date_creation.data
db.session.commit()
return redirect(url_for('home._blogs_'))
return render_template('home/blog.html', action="Edit", add_article=add_article, form=form, blog=blog, title="Edit blog")
###第二个视图
@home.route("/article/<int:id_article>/comment", methods=["POST"])
def comment_post(id_article):
article = Article.query.get_or_404(id_article)
form_comment = AddCommentForm()
if form_comment.validate_on_submit():
comment = Comment(
body_comment_article = form_comment.body_comment_article.data,
posted_name = form_comment.posted_name.data ,
date_creation = datetime.datetime.now(),
id_articles=article.id)
db.session.add(comment)
db.session.commit()
flash("Your comment has been added to the article", "success")
return redirect(url_for("home.show_article", id=article.id , url_path=article.url_path))
return render_template("/home/blog.html", title="Comment Post", add_comment=add_comment, form_comment=form_comment, article=article)
代码返回以下错误:
UndefinedError: 'form_comment' is undefined
能帮我吗,谢谢
答案 0 :(得分:0)
解决方法是。 在我的第一个视图中,我通过了form_comment,并在模板{%if for_comment%} ... {%endif%}中添加了if语句
@home.route('/blogs/Article/<int:id>/<string:url_path>', methods=['GET'])
def show_article(id, url_path):
add_article = False
blog = Article.query.get_or_404(id)
form = ArticleForm(obj=blog)
form_comment = AddCommentForm()
if form.validate_on_submit():
blog.titre = form.titre.data
blog.url_path = form.url_path.data
blog.writ_by = form.writ_by.data
blog.body = form.body.data
blog.date_creation = form.date_creation.data
db.session.commit()
return redirect(url_for('home._blogs_'))
return render_template('home/blog.html', action="Edit", add_article=add_article, form=form,form_comment=form_comment, blog=blog, title="Edit blog")