Search code examples
htmlflask

How to send data to form textbox in flask app


I trying to build simple web application, while doing I am able to get the data from form to flask but while sending back or to another html form data is not going to textbox. Could anyone please help?

I am taking the mobile number in the index page checking if exists if not going to create screen, there the mobile num is not getting populated in the textbox. But I am able to send the data to message.

app.py

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from send_mail import send_mail

app = Flask(__name__)

ENV = 'dev'

if ENV == 'dev':
    app.debug = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Password-1@localhost/lexus'
else:
    app.debug = False
    app.config['SQLALCHEMY_DATABASE_URI'] = ''

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Feedback(db.Model):
    __tablename__ = 'feedback'
    id = db.Column(db.Integer, primary_key=True)
    mobile_num = db.Column(db.BigInteger, unique=True)
    cus_name = db.Column(db.String(200))
    aadhar = db.Column(db.BigInteger)
    cus_address = db.Column(db.Text())

    def __init__(self, mobile_num, cus_name, aadhar, cus_address):
        self.mobile_num = mobile_num
        self.cus_name = cus_name
        self.aadhar = aadhar
        self.cus_address = cus_address

with app.app_context():
    db.create_all()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST','GET'])
def submit():
    if request.method == 'POST':       
        mobile_num = request.form['mobile_num']
        cus_name = request.form['cus_name']
        aadhar = request.form['aadhar']
        cus_address = request.form['cus_address']
        cus_btn = request.form['cus_btn']
        #print(cus_btn)
        if cus_btn=='Search':
            if mobile_num == '':
                return render_template('index.html', message='Please enter required fields:')
            if db.session.query(Feedback).filter(Feedback.mobile_num == mobile_num).count() == 0:
                return render_template('create.html',message=mobile_num)
            else:
                qry_result = db.session.query(Feedback).filter(Feedback.mobile_num == mobile_num).all()
                for feedback_entry in qry_result:
                    print(feedback_entry.cus_name)
                    return render_template('index.html', mobile_num=feedback_entry.mobile_num,cus_name=feedback_entry.cus_name,aadhar=feedback_entry.aadhar,cus_address=feedback_entry.cus_address)

@app.route('/create', methods=['POST','GET'])
def create():
    if request.method == 'POST': 
        mobile_num = request.form['mobile_num']
        cus_name = request.form['cus_name']
        aadhar = request.form['aadhar']
        cus_address = request.form['cus_address']

        data = Feedback(mobile_num, cus_name, aadhar, cus_address)
        db.session.add(data)
        db.session.commit()
        #send_mail(mobile_num, cus_name, aadhar, cus_address)
        return render_template('index.html')

if __name__ == '__main__':
    app.run()

```python



create.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="../static/style.css" />
        <title>TRC Group</title>
      </head>
      <body>
        <div class="container">
          <img src="../static/TRC-logo.png" alt="TRC" class="logo" />
          {% if message %}
          <p class="message">{{ message | safe }}</p>
          {% endif %}
          <form action="/create" method="POST">
            <div class="form-group">
              <h3>Mobile Number</h3>
              <input
                type="tel"
                pattern="[0-9]{10}"
                name="mob_num"
                placeholder="1234567890"
              />
            </div>
            <div class="form-group">
              <h3>Name:</h3>
              <input type="text" name="cus_name" value="" />
            </div>
            <div class="form-group">
              <h3>aadhar</h3>
              <input type="text" name="aadhar" value="" pattern="[0-9]{12}"/>          
            </div>
            <div class="form-group">
              <h3>cus_address</h3>
              <textarea
                name="cus_address"
                id=""
                cols="30"
                rows="3"
                placeholder="Address"
              ></textarea>  
            </div>
            <input type="submit" name="cus_btn" value="Create" class="btn" />
          </form>
        </div>
      </body>
    </html>

I tried changing to GET but still not able to populate. Data is getting passed to message field but not for the textbox.

Solution

  • You have the template render the mobile_num as some kind of message in a paragraph tag.
    You have to put it in the value property of the textbox

              <input
                type="tel"
                pattern="[0-9]{10}"
                name="mob_num"
                placeholder="1234567890"
                value="{{ message | safe }}"  
              />