首页 > 解决方案 > 烧瓶编辑方法不起作用,找不到原因

问题描述

我正在尝试添加一个按钮,将我重定向到带有空文本字段的新页面。问题是,当我单击按钮时,出现内部服务器错误,并且由于服务器不可能超载,这意味着某处的代码存在错误。由于我无法弄清楚,我发布了这个问题。我希望我提供了足够的代码和信息。另外,我不是经验丰富的 python/flask 开发人员,我正在为一个学校项目做这件事。提前感谢您可能给我的任何帮助或提示!

编辑我已经包含了我需要的所有东西,以便它工作,服务器正在运行,当我按下按钮时我只会得到一个错误(我提供的最底层代码)。

蟒蛇代码:

@app.route('/apartments/comments/<int:apartment_id>/<int:comment_id>/edit', methods=['GET', 'POST'])
@login_required
def comment_edit(comment_id):
    comment = Comment.query.filter_by(id=comment_id).first()
    form = CommentForm()
    if not comment:
        return render_template('errors/404.html'), 404
    if form.validate_on_submit() and comment.user_id == current_user.id:
        db.session.query(Comment).filter(
            Comment.id == comment.id).update({Comment.comment:form.comment.data})
        db.session.commit()
        flash("Comment edited Successfully!")
        return redirect(url_for('apartment_show', apartment_id=apartment.id))

    return render_template('comment_edit.html', comment=comment, form=form)

SQLalchemy 表:

class Comment(db.Model, UserMixin):
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
    apartment_id = db.Column(db.Integer, db.ForeignKey(Apartment.id), nullable=False)
    comment = db.Column(db.Text, nullable=False)

WT表格:

class CommentForm(FlaskForm):
    user_id = HiddenField('user_id', validators=[InputRequired()])
    apartment_id = HiddenField('apartment_id', validators=[InputRequired()])
    comment = TextAreaField('comment', validators=[InputRequired()],
    render_kw={"placeholder": "Your comment here!"}) #this is on 1 line, I think it doesnt matter but just saying.

评论编辑.html:

{% extends "layouts/layout.html" %}
{% block title %}Edit Comment{% endblock title %}
{% block head %}
{% endblock head %}
{% block body %}
  <form class="body" method="post" action="{{ url_for('comment_edit',comment_id=comment.id, apartment_id=apartment.id) }}">
    {{ form.csrf_token }}
    {{ form.user_id(value=current_user.get_id()) }}
    <label>Comment: </label><br>{{ form.name(value=Comment.comment, rows='3',cols='100') }}<br>
    <button type="submit">Edit Comment</button>
  </form>
{% endblock body %}

我如何访问和转到 comment_edit 方法:

<a style="float: right" href="{{ url_for('comment_edit', comment_id=comment.id, apartment_id=apartment.id) }}">Edit Comment</a>

标签: flaskflask-sqlalchemyflask-wtforms

解决方案


在这一行中,您需要将 2 个参数传递给您的路线:

@app.route('/apartments/comments/<int:apartment_id>/<int:comment_id>/edit', methods=['GET', 'POST'])

即,apartment_idcomment_id

但是,这一行:

def comment_edit(comment_id):

定义函数时只有一个参数comment_edit。您需要将其更改为:

def comment_edit(apartment_id, comment_id):

推荐阅读