Query and display one row based on user input in jinja

Viewed 39

I want to print one table row based on the user input. I am getting the user input (id) via HTML and Python, here:

html file:

<tbody class="table-group-divider">
        {% for course in user.courses %}
        <tr>
            <!-- here an ID gets rendered from the table, and user clicks on it -->
            <td><a href="course_detail/{{ course.id }}">{{ course.course_name }}</a></td>
            <td class="align-middle">
                {% for student in course.students %}
                <span>{{ student.student_name }}</span><br>
                {% endfor %}
            </td>
            <td>{{ course.course_day }} {{ course.course_time }}</td>
            <td>{{ course.course_language }}</td>
        </tr>
        {% endfor %}
    </tbody>

app.py:

@app.route('/course_detail/<id>', methods=["GET", "POST"])
@login_required
def course_detail(id):
return render_template("course_detail.html", user=current_user, id=id)

My logic is to loop through the table, and if id provided by user matches id (primary key) in table, I found what I want to display, and then display it. However, my attempt does not print anything:

<!-- setting the ID from url/html, basically what user clicked -->
{% set id = id %}

{% for course in user.courses %}
    {% if course.id == id %}
        <p>im working</p>
    {% endif %}
{% endfor %}

I get the id from user, but I can't seem to compare it with course.id so I could display the whole row. Is there a problem with my if statement?

Edit: If I hardcode the if statement to be for example {% if course.id == 2 %} (or any other valid course.id from the table), the information gets printed with no issues.

1 Answers

While I'm not sure why the original proposition doesn't work, I managed to reach my goal via querying my database in app.py, not my html file.

@app.route('/course_detail/<id>', methods=["GET", "POST"])
@login_required
def course_detail(id):

    # query the id in db
    db_id = Course.query.filter_by(id=id).first()
    # save all info into variables
    db_course_name = db_id.course_name
    db_course_language = db_id.course_language
    db_course_day = db_id.course_day
    db_course_time = db_id.course_time
    db_hourly_rate = db_id.hourly_rate
    # send the variables and print them in html
    return render_template("course_detail.html", user=current_user, pageid=db_id, db_course_name=db_course_name, db_course_language=db_course_language, db_course_day=db_course_day, db_course_time=db_course_time, db_hourly_rate=db_hourly_rate)

Then I simply printed the variables using double curly braces. Not sure if this is the best design, but it certainly feels better than my previous attempt.

Related