Raad Altaie
Raad Altaie

Reputation: 1241

how to make POST method works for two different forms on same page with flask?

how to make POST method works for two different forms on same page with flask ?

Here's my code from main __int__.py file for flask / python

@app.route('/', methods=['GET', 'POST'])
@app.route('/login/', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['email'] != '1' or \
                request.form['password'] != '1':
            flash('Invalid Credentials')
        else:
            flash('You were successfully logged in')
            return redirect(url_for('dashborad'))
    return render_template('login.html', error=error)


@app.route('/', methods=['GET', 'POST'])
@app.route('/register/', methods=['GET', 'POST'])
def register():
    try:
        if request.method == 'POST':
            email = request.form['email1']
            name = request.form['name1']
            password = request.form['password1']

            cur, db = connection()
            x = cur.execute(" SELECT * FROM users WHERE email = (%s)" ,[escape(email)])

            if int(x) > 0:
                flash ("email already used ")
                return render_template ("register.html")
            else:
                cur.execute("INSERT INTO users (first_name, email, password) VALUES (%s, %s, %s);" ,(escape(name), escape(email), escape(password) ))

                db.commit()
        return render_template ("register.html")

right now python is reading POST method for first @app.route login form only

is there any easy way to get such line in python ?

if request.method == 'POST' for form 1

and

 if request.method == 'POST' for form 2

Upvotes: 1

Views: 7756

Answers (2)

Raad Altaie
Raad Altaie

Reputation: 1241

I figured out the way to do that using Ajax request in JavaScript for each form on the same page

Example:-

HTML form

<form onsubmit="formSumbit()">
  email: <input id="email" type="text">
  password: <input id="password" type="password">
  <input type="submit">
</form>

JavaScript POST request function for each form it will look something like this

function formSumbit(event) {
    event.preventDefault()
    fetch("http://yourwebsite.com/login", {
        method: "POST",
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: document.getElementById('email').value, password: document.getElementById('password').value })
    }).then((res) => {
        console.log(res);
        return res.json();
    }).then((data) => {
        console.log(data);
    }).catch((err) => {
        console.log(err);
    });
}

And to use two POST route handlers for each form in Flask or pass extra parameter called 'form1' or 'form2' and check for the parameter in Flask route handler.

Upvotes: 0

vutsuak
vutsuak

Reputation: 62

I guess you want something like the starting page of LinkedIn

To achieve that in Flask create the HTML template as :

<input type="submit" name="btn" value="Save">
<input type="submit" name="btn" value="Cancel">

and then you can validate by:

if request.form["btn"]=="Save":
    if request.method== 'POST':
        doSomething()

This solution might work

Upvotes: 1

Related Questions