1

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
Raad Altaie
  • 1,025
  • 1
  • 15
  • 28

2 Answers2

1

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

vutsuak
  • 64
  • 8
  • thank you for your answer , but it gave this error 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. – Raad Altaie Jun 15 '17 at 08:25
  • [use this](https://stackoverflow.com/questions/21949452/wtforms-two-forms-on-the-same-page) – vutsuak Jun 15 '17 at 10:54
  • i think i have to use WTForms after all i have a project to use as minimum as possible of frameworks thanks again buddy – Raad Altaie Jun 15 '17 at 10:56
  • yes I guess you have to.Flask has an easy API for that [link](https://flask-wtf.readthedocs.io/en/stable/) – vutsuak Jun 15 '17 at 10:57
0

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.

Raad Altaie
  • 1,025
  • 1
  • 15
  • 28