Search code examples
flaskflask-sqlalchemyflask-security

Flask-security delete user return an error


I'm trying to add a delete button on my users admin page in a flask app.

But I already have this error when I click on button :

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.str' is not mapped

This is my adminusers.html file :

{% extends 'base.html' %}
{% block main %}
<main>
  <table class="table table-striped users">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Email</th>
        <th scope="col">Roles</th>
        <th scope="col" class="text-center">Delete</th>
      </tr>
    </thead>
    <tbody>
    {% for user in users %}
      <tr>
        <th scope="row">{{ user.id }}</th>
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
        <td>
          {% for role in user.roles %}
            {{role.name}};
          {% endfor %}
        </td>
        <td style="text-align: center;"><a href="{{ url_for('delete_user', user=user) }}" style="color:red" ><i class="fas fa-times"></i></a></td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
</main>
{% endblock main %}

And my app.py file :

@app.route('/adminusers')
def list_users():
    users= User.query.all()
    return render_template('adminusers.html', users=users)

@app.route('/delete_user/<user>')
def delete_user(user):
    user_datastore.delete_user(user=user)
    db.session.commit()
    return redirect(url_for('adminusers'))

I'm trying to use the 'email' or 'name' but it already return an error


Solution

  • Thanks @pjcunningham, like that it works :

    @app.route('/delete_user/<id>')
    def delete_user(id):
        user = user_datastore.get_user(id)
        user_datastore.delete_user(user)
        db.session.commit()
        return redirect(url_for('adminusers'))