skip to Main Content

I am new to flask and HTML.

I am creating a user management tool with buttons to do actions (methods) in flask.

I want to add a button where the user can delete a user. The logic to delete a user uses a user_id, which I want to put in my action URL so it can be deleted. I am used to adding variables with

`${variable}`

but that doesn’t seem to work here.

Here is my HTML code. users is an array passed in through flask, containing each item listed in the table per user.

<body>
    <h1>User Management</h1>
    <table>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>User ID</th>
            <th>Email</th>
        </tr>
         {% for u in users %}
        <tr>
            {% for el in u[0:] %}
                <td>{{el}}</td>
            {% endfor %}
            <td>
                <form action="/delete_user/`${u[2]}`" method="post">
                    <button type="submit">Delete User</button>
                </form>
            </td>
        </tr>

    </table>
</body>

Python code:

@app.route('/delete_user/<user_id>')
def deleteuser(user_id):
  #logic here to delete user with user_Id

How can I insert the variable value of u[2] into the action URL?

2

Answers


  1. To access a variable using the Jinja templating engine, you can use this syntax: {{ expression }}.

    So in your case, this is how you would insert u[2] into a form action.

    <form action="/delete_user/{{ u[2] }}" method="post">
        <button type="submit">Delete User</button>
    </form>
    

    The syntax you were using before: ${u[2]}, is JavaScript syntax.

    To read more on Jinja templating syntax, check out this section in the docs.

    Login or Signup to reply.
  2. With jinja (Flask templating mechanism) you can use {{ }} to substitute a template variable. It will resolved before jscript parsing, for example:

    {% for u in users %}
     <td>
      <form action="/delete_user/{{u[2]}}`" method="post">
      <button type="submit">Delete User</button>
     </form>
    </td>
    

    Jinja variables: https://jinja.palletsprojects.com/en/3.0.x/templates/#variables

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search