jinja2.exceptions.UndefinedError: 'to_user' is undefined

jinja2.exceptions.UndefinedError: 'to_user' is undefined

我正在尝试在 FLASK 和 html 页面中创建功能以允许用户相互评分 - 一个用户可以给另一个用户评分,但我收到此错误:jinja2.exceptions.UndefinedError: 'to_user' 未定义。请问有人知道怎么解决吗?

     @app.route('/user/<int:id>/add-rating/', methods=['GET', 'POST'])
        def rating(id):
            form = RatingForm()
            if form.validate_on_submit():
                from_user = current_user.id
                to_user = Users.query.get_or_404(id)
                content = form.content.data
                rating = Ratings(from_user = from_user, to_user = to_user, content = content)
                db.session.add(rating)
                db.session.commit()
                flash(' posted')
            return render_template('add_rating.html', form=form)



class Ratings(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    from_user = db.Column(db.Integer, db.ForeignKey('users.id'))
    to_user = db.Column(db.Integer, db.ForeignKey('users.id'))



{% if current_user.is_authenticated %}
<h1>Ohodnotit uživatele {{to_user.username}}</h1> 
<br/>
<div class="shadow p-3 mb-5 bg-body rounded">
<form method="POST">
    {{ form.hidden_tag() }}

    {{ form.content.label(class="form-label") }}
    {{ form.content(class="form-control", rows="5") }}

    <br/>
    {{ form.submit(class="btn btn-secondary") }}
</form>
</div>
{% else %}
<h1>Abys mohl ohodnotit uživatele, musíš být přihášen</h1>
<h2><a href="{{url_for('login')}}"> Přihlas se zde</a></h2>
{% endif %}
    
    

首先你需要加载to_user变量并将其传递给模板:

@app.route('/user/<int:id>/add-rating/', methods=['GET', 'POST'])
def rating(id):
    to_user = Users.query.get_or_404(id)
    form = RatingForm()
    if form.validate_on_submit():
        from_user = current_user.id
        content = form.content.data
        rating = Ratings(from_user = from_user, to_user = to_user, content = content)
        db.session.add(rating)
        db.session.commit()
        flash(' posted')
    return render_template('add_rating.html', form=form, to_user=to_user)