-1

Hi I'm coding review page with Flask but struggling with creating delete button. According to my code, when delete button is clicked, KeyError appears. There are only two rows in the review table which are Writer and Content. I pasted showing and deleting review API code, also with Server side Delete function.

Is my way alright to delete code by sending title and review from client to server then delete the object in DB which matches title and review which is sent by client? I'm wondering why KeyError is appeared. I beg for your help! Thanks for reading.

  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 2088, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/Users/min05099/sparta/projects/detailPage/app.py", line 19, in write_review
    review_receive = request.form['review_give']
  File "/Users/min05099/sparta/projects/detailPage/venv/lib/python3.8/site-packages/werkzeug/datastructures.py", line 377, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'review_give' ```



```function showReview() {
                $.ajax({
                    type: "GET",
                    url: "/review",
                    data: {},
                    success: function (response) {
                        let reviews = response['all_reviews']
                        for (let i = 0; i < reviews.length; i++) {
                            let title = reviews[i]['title']
                            let review = reviews[i]['review']

                            let temp_html = `<tr>
                                               <td>${title}</td>
                                               <td>${review}</td>
                                               <td><button onclick="deleteReview('${title, review}')">delete</button></td>
                                           </tr>`
                            $('#reviews-box').append(temp_html)
                        }
                    }
                    }
                )
            }


            function deleteReview(title, review) {
                            $.ajax({
                                type: 'POST',
                                url: '/review',
                                data: {title_give:title, review_give:review},
                                success: function (response) {
                                    alert(response['msg']);
                                    window.location.reload()
                                }
                            });
                        } ```

```@app.route('/review', methods=['POST'])
def delete_review():
    title_receive  = request.form['title_give']
    review_receive = request.form['review_give']
    db.miniProject.delete_one({'title': title_receive, 'review': review_receive})
    return jsonify({'msg': 'Successfully Delete!'})```
Meen ki
  • 35
  • 7
  • Check [this](https://stackoverflow.com/questions/27158573/how-to-delete-a-record-by-id-in-flask-sqlalchemy), it may answer your question – Paras Gupta Jun 10 '21 at 02:46

1 Answers1

0

The issue stems from your string interpolation when generating the button.

${title, review} only injects the value of review. Since your deleteReview only receives one argument, the review_give field in the data of ajax call is left blank, leading to the corresponding missing key in your flask app.

This is how you correctly do your string interpolation:

let temp_html = `<tr>
        <td>${title}</td>
        <td>${review}</td>
        <td><button onclick="deleteReview('${title}, ${review}')">delete</button></td>
    </tr>`

Also, instead of deleting your reviews by title and review body, it would be better an easier to assign an ID to each of the review on the server side. You can then delete reviews based on this ID.

wxker
  • 1,841
  • 1
  • 6
  • 16
  • I have a further question. I'm trying to delete review by its id which is allocated from DB, but I have no idea how to get id when coding index.html. Would you give a solution about it. – Meen ki Jun 10 '21 at 05:00
  • The same way you got the title and body of each review. You need to pass the id from the flask app to the front end through the `showReview` function – wxker Jun 10 '21 at 11:31
  • I appreciate a lot for your effort! Good Luck! – Meen ki Jun 11 '21 at 02:34