samedi 27 mars 2021

The template is not redirecting accordingly in Flask

app.py

@app.route('/login',methods=['POST','GET'])
def login():
    customer_form = CustomerLogin(request.form)     
    if request.method == 'POST':
        if customer_form.validate_on_submit():
            
    ##        data = request.form
            username = customer_form.username1.data
            password = customer_form.password1.data
            cursor = mysql.connection.cursor()
            query = '''SELECT username,password FROM customers'''
            cursor.execute(query)
            data = cursor.fetchall()
            mysql.connection.commit()
            cursor.close()
            accounts_dict = {}
            for x,y in data:
                accounts_dict[x] = y
            if username in accounts_dict:
                if password == accounts_dict[username]:
                    cursor = mysql.connection.cursor()
                    query = 'SELECT name FROM customers WHERE username = %s'
                    cursor.execute(query,(username,))
                    result = cursor.fetchone()
                    mysql.connection.commit()
                    cursor.close()
                    return redirect('/homepage_loggedin',name=result[0])
                else:
                    error = 'Incorrect password! Please try again!'
                    return render_template('loginPage.html',error=error)
            else:
                error = 'No current user!'
                return render_template('loginPage.html',error=error)

@app.route('/homepage_loggedin/<string:name>')
@login_required
def homepage_loggedin(name):
    return render_template('homepage_loggedin.html',name=name)

models.py

class CustomerLogin(FlaskForm):
    username1 = StringField('Username',[validators.Length(min=6,max=100)])
    password1 = PasswordField('Password',[validators.Required("Please enter a password.")])
    submit1 = SubmitField('Login')  

loginPage.html

<form method="POST" action="" name="customer_login">
                <h3 style="text-align:center;padding-bottom:10px;">Customer Login Portal</h3>
                <p></p>
                <p></p>
       
                
                <p></p>
                
                <p></p>
            </form>

I do not understand what is the reason when I entered the data on the template loginPage.html and clicked the login button then it still remains on the same page. I would like to redirect to the homepage if the username and password are correct so what is the best way in order to have the login page redirect to homepage after login?




Aucun commentaire:

Enregistrer un commentaire