Issue with passing python function to jinja

Viewed 19

I am working on a Flask web app and I am at a point where I want the admin of the site to be able to approve/deny users. The issue I am facing is that I am trying to call Python functions in html/jinja template. Here is a look. demo

In the user_approval.html file

``

<table id="user-approval" class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Full Name:</th>
            <th>Address:</th>
            <th>DOB:</th>
            <th>Email:</th>
            <th></th>
            <th></th>
        </tr>
    </thead>

    <tbody>
        {% for user in users.items %}
            <tr>
                <td>{{ user.a_name }}</td>
                <td>{{ user.a_address }}</td>
                <td>{{ user.a_dob }}</td>
                <td>{{ user.a_email }}</td>
                <td><button id="approve-user-btn" onclick="{{ user_approve }}">approve</button></td>
                <td><button id="deny-user-btn" onclick="{{ user_deny }}">deny</button></td>
            </tr>
        {% endfor %}
    </tbody>

    <tfoot>
        <tr>
            <th>Full Name:</th>
            <th>Address:</th>
            <th>DOB:</th>
            <th>Email:</th>
            <th></th>
            <th></th>
        </tr>
    </tfoot>
</table>

``

I would need to pass the user_id as an argument. I tried to do something like this

<button id="approve-user-btn" onclick="{{ user_approve(user.id) }}">approve</button>

Which calls the functions before admin clicks.

1 Answers

This is not going to work, the onclick event can be used to run Javascript, but in this case you should rather create a route in Jinja to run Pyton code. You need to add a <form> in your HTML too, and in your form you set the target accordingly (using the function url_for). Change the button like this too, so it behaves like a submit element:

<button id="approve-user-btn" type="submit"...

or

<input id="approve-user-btn" type="submit"...

And probably add a hidden field for the user ID as well. This value will be included in the form (POST) request.

Related