سؤال

This is a function which (in a GET request) receives a case_url and case_key and serves the corresponding case (using mongoDB) to a html template called detail_case. Im trying to add a feature where when a form is filled(on this same page detail_case) and it is submitted, it should submit a POST request to the same function and the code under 'if request.method=="POST"' should get executed.

@app.route('/case/<case_url>/<case_key>', methods=["GET","POST"])
def serve_case(case_url,case_key):
"""for saving a comment in db.comments"""
if request.method == "POST":    

    text=request.form['comment_text']
    #code which inserts it in the database

    return redirect(url_for('serve_case', \
    case_url=case_url,\
    case_key="Highlights"))

"""
Function serves the case as per the key indicated in the URL
"""

#corresponding code here which fills values of variables and sends it to another page

return render_template('detail_case.html')

The problem is that I don't think the POST request is ever executed. This is the html code on the template page detail_case-

<textarea placeholder="Please enter your comments here" action="{{ url_for('serve_case',case_url=case_url,case_key=case_key)}}" method="POST" name="comment_text" rows="6"></textarea><br />

The problem i think is the action field. I don't know how should I send the variable comment_text to my function. Infact, the code under POST does not get executed when I submit. Basically the issue is that during a GET request, it sends 2 variables which are needed in the parameters of the function serve_case. During my POST request, well, I don't know how to exactly frame the action field. If I send no parameters, its an error. If I don't send it to the same function, then how will it execute the POST code? Could someone please suggest sumthing? i'm pretty new to flask, i'm editing someone else's code

هل كانت مفيدة؟

المحلول

You need to submit the POST request (for example through form) like below:

<form action="{{ url_for('serve_case',case_url=case_url,case_key=case_key)}}" method="POST">
 <input type="text" placeholder="Please enter your comments here">
 <input type="submit"   name="comment_text" rows="6"><br />
</form>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top