Python flask 405 error

Asked 2 years ago, Updated 2 years ago, 131 views

index.html

{% for obj in data_list%}
      <!-- single item -->
      <div class="item my-3">
      <h5 class="item-name text-capitalize">{{obj.contents}}</h5>
      <div class="item-icons">
        <a href="{{url_for('delete')}}" }" name="id" value="{{obj._id}}" class="delete-item item-icon">
        <i class="far fa-times-circle"></i>
       </a>
      </div>
     </div>
      <!-- end of single item -->
      {% {% endfor %}

list.py

@app.route('/delete', methods=['POST'])
def delete():
    idx=request.values.get('id')
    db.delete_todo(idx)
    return '''
                <script>
                    alert("Deleted")
                    location.href="."
                </script>
              '''

db.py

def delete_todo(idx):
    conn = mongodb.get_conn()
    conn.delete_one({"_id":idx})

In index.html, click where the a tag is and db.I want to do an operation to delete data from py and remove it from the screen, but when I click the tag a, the method is not allowed for the requested URL. This 405 The D.B. wrote the Mongo DB.B.

What's wrong? It seems easy to google and study by myself, but it's stuckㅜ<

python flask html mongodb

2022-09-20 19:36

1 Answers

HTTP 405 means "There is no way to handle it with that method." You can request /delete with POST method, but when you press the button, you are required to request GET/delete.This is because the a tag handles the GET request. So the legitimate error 405 is returned.

The simplest ignorant hotfix would be like this is how it works.

<form action="POST" action="{{ url_for('delete') }}">
    <input type="hidden" name="id" value="{{ obj._id }}" />
    <button type="submit" class="delete-item item-icon">
        <i class="far fa-times-circle"></i>
    </button>
</form>

The key point is to find a way to send a POST request and request /delete in that way. If you make it better, for example, these scripts will be mobilized.

$('body').on('click', '.delete-item', function () {
    $.ajax({
        type: 'POST',
        url: '/delete',
        data: {id: obj._id}
    });
});

If you understand, apply it well.


2022-09-20 19:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.