Home > OS >  jinja2.exceptions.UndefinedError: 'to_user' is undefined
jinja2.exceptions.UndefinedError: 'to_user' is undefined

Time:03-02

i am trying to create function in FLASK and html page to allow users to rate each other - one user can give rating to enother user, but i am getting this error: jinja2.exceptions.UndefinedError: 'to_user' is undefined. Does anyone know, how to solve it please?

     @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 >
<form method="POST">
    {{ form.hidden_tag() }}

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

    <br/>
    {{ form.submit() }}
</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 %}
    
    

CodePudding user response:

First you need to load the to_user variable and pass it to the template:

@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)
  • Related