Home > Net >  I am storing data in MongoDB and want to fetch that data based on user query
I am storing data in MongoDB and want to fetch that data based on user query

Time:02-11

I am storing data in MongoDB, now I have created a flask webpage which lets user submit an ID and based on ID (which is stored in database) it should return that data. My requirement is that after entering ID and clicking on Submit button, Flask should display a message or prompt which contains the data. I am kind of stuck. Below is the code.

app.py

@app.route('/status', methods = ["GET", "POST"])
def status():
    
    return render_template("status.html")

status.html

<h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" method="get">
    <div >
      <div >
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div >
        <input autofocus type="text" name="id" id="id"  placeholder="Enter ID" required>
      </div>
    </div>
    
    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>

ID is stored in database already. In simpler terms, I want the code to search for that specific ID and return the associated data of that ID. How should I code the status function to do that?

CodePudding user response:

In your case you have to do this :
first you have to change the method to POST since you are posting data.
Then you need add the action with the url you are send data to in your case it would be status

<h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" action="{{ url_for('status')}}" method="POST">
    <div >
      <div >
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div >
        <input autofocus type="text" name="id" id="id"  placeholder="Enter ID" required>
      </div>
    </div>
    
    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>

in app.py you need to receive the var from the form you need to use request module

from flask import request

then your function need look like this

@app.route('/status', methods=['POST', 'GET'])
def status():
    if request.method == 'POST':
        your_var = request.form['id']
    return render_template('status.html')

hope this solve your issue

  • Related