0

I'm newbie to flask,I have such a form:

<form class="form" action={{ url_for('/login') }} method="POST">
        <input type="text" name="usename" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit" id="login-button">Login</button>
</form>

I use request.form()and request.form.get() to get submitted values,but the result is always the same**"GET / HTTP/1.1" 200 -**

@app.route('/login',methods=['POST','GET'])
def login():
    name=request.form['usename']
    password=request.form['password']
    form_data=request.form.get('usename')
    print name,password,form_data
    return render_template('login.html')

And I try visiting /login ,it shows Bad Request.But when it is modified to such,it's ok.It seems my request statement block is incorrect.

@app.route('/login',methods=['POST','GET'])
def login():
    return render_template('login.html')
M.Mark
  • 63
  • 2
  • 13

3 Answers3

0

It's because of form action change the

action="{{url_for('index')}}" 

Your form does not post actually and you are try to get values. And don't forget to add a view function named index or you can use instead login instead index

metmirr
  • 4,234
  • 2
  • 21
  • 34
0

i guess you are trying to get those values from login.html file. If it is so you have to use something like this

    @app.route('/login',methods = ['GET','POST'])
    def login():
         if request.method =='POST':
              name=request.form['usename']
              password=request.form['password']
              form_data=request.form.get('usename')
              print name,password,form_data
         return render_template('login.html')
manoj prashant k
  • 339
  • 1
  • 13
0

try leaving the action field emtpy.

<form class="form" action="" method="POST">

leaving it empty will post to the same location where the form was downloaded from, which I guess is your use case here.

[1] Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Community
  • 1
  • 1
Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55