Python Flask not deleting correct id from SQLAlchemy database

Issue

I have an HTML table which pulls data from an SQLAlchemy database.

In this table, for each row, I have a Delete button, which should delete that row and database entry when I click on it.

The issue I have, is that if I try to delete any row in this table, it deletes only the first row (see image below) and the associated data in the database.

The row and the data I wanted deleted remain unchanged (the 3rd row in the image below).

enter image description here

If I click Delete on the first row in the table, it works without issues.

The Update button works as indented (updating the correct entry)

This is the database model I have:

class ActualPost(db.Model):
    __tablename__ = 'actualpost'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title_actual = db.Column(db.String(30), nullable=False, default='actual')
    category_actual = db.Column(db.String(30), nullable=False, default=None)
    actual_amount_name = db.Column(db.String(30), nullable=True)
    actual_amount = db.Column(db.Float, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comments = db.Column(db.Text, nullable=True)

    def __repr__(self):
        return f"ActualPost('{self.title_actual}, '{self.category_actual}'\
        , '{self.actual_amount_name}', '{self.actual_amount}'\
        , '{self.date_posted}', '{self.comments}')"

Here are my routes (Update and Delete)

@posts.route("/post/<int:post_id>/update_actual", methods=['GET', 'POST'])
@login_required
def update_actual_post(post_id):
    post = ActualPost.query.get_or_404(post_id)
    if post.actual_author != current_user:
        abort(403)
    form = PostActualForm()
    if form.validate_on_submit():
        post.title_actual = form.title_actual.data
        post.category_actual = form.category_actual.data
        post.actual_amount_name = form.actual_amount_name.data.name
        post.actual_amount = form.actual_amount.data
        post.comments = form.comments.data
        db.session.commit()
        flash('Your post has been updated!', 'success')
        return redirect(url_for('main.actual', post_id=post.id))
    elif request.method == 'GET':
        form.title_actual.data = post.title_actual
        form.category_actual.data= post.category_actual
        form.actual_amount_name.data = post.actual_amount_name
        form.actual_amount.data = post.actual_amount
        form.comments.data = post.comments
    return render_template('create_actual_post.html', title='Update Actual',
                           form=form, legend='Update Actual')


@posts.route("/post/<int:post_id>/delete_actual", methods=['POST'])
@login_required
def delete_actual_post(post_id):
    post = ActualPost.query.get_or_404(post_id)
    if post.actual_author != current_user:
        abort(403)
    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted!', 'success')
    return redirect(url_for('main.actual', post_id=post.id))

This is the HTML code I use for the Delete button:

<div class="modal-footer">
   <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
   <form action="{{ url_for('posts.delete_actual_post', post_id = post.id) }}" method="post">
     <input class="btn btn-danger" type="submit" value="Delete">
   </form>
</div>

Solution

Here is my code to delete particular row by id. You can co-relate it with your code

SQL-alchemy Modal :

class Componants(db.Model):
    __tablename__ = 'componants'
    id = db.Column(db.Integer, primary_key=True)
    cmp_options = db.Column(db.Text, default=None)
    updated_at = db.Column(db.DateTime, nullable=True)
    created_at = db.Column(db.DateTime, nullable=True)


def __init__(self , cmp_options ):
    self.cmp_options = cmp_options 
    self.created_at = datetime.now()
    self.updated_at = datetime.now()

def __repr__(self):
    return '<id {}>'.format(self.id)

Controller :

@componants_blueprint.route('/delete_component/<component_id>')
@login_required
def delete_component(component_id):
    component = Componants.query.filter_by(id=component_id).first_or_404()
    db.session.delete(component)
    db.session.commit() 
    return True

View:

              <tbody>
                {% for item in all_components %}
                <tr>
                  <td>{{ item.id }}</td>
                  <td>{{ item.cmp_options }}</td>
                  <td>{{ item.created_at }}</td>
                  <td class="text-center"> 
                    <a href="{{ url_for('componants.delete_component', component_id=item.id) }}" title="Delete" class="far fa-trash-alt"></a>
                  </td>    
                </tr>
                {% endfor %}
            </tbody>

Answered By – Chirag Vora

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published