I'm am using flask and trying to access my homepage after the login and when trying to click on the log in button, the endpoint for the home is not getting called.
Below is my app.py file.
from flask import Flask, request, jsonify, render_template, redirect, url_for
from tensorflow import keras
app = Flask(__name__, template_folder='templates')
@app.route('/')
def home():
print('success1')
return render_template(r'index.html')
@app.route('/success')
def success():
# return 'logged in successfully'
print('success')
render_template(r'Home.html')
if __name__ == "__main__":
app.run()
Below is my index.html code. (login form) Only the tag is added below.
<form id = "login-form" action="" method="post">
<div >
<input type="text" name="username" id="username" placeholder="Username">
</div>
<br>
<div >
<input type="password" id="password" name="password" placeholder="Password">
</div>
<br>
<div >
<button type="button" id="login-form-submit">Sign In</button>
</div>
</form>
Below is the validation.js file I have created.
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
if (username === "user" && password === "user123") {
alert("You have successfully logged in.");
window.location.replace("{{ url_for('success') }}");
} else {
loginErrorMsg.style.opacity = 1;
}
})
When I click on the sigh in button, I do get the alert saying 'you have successfully logged in' but I'm not getting redirected to the home.html. I suspect that something is wrong in the way that I call the endpoint in my javascript file.
Kindly help me with this.
CodePudding user response:
I can't help you with the Javascript validation but the below python and html code works for me:
@app.route('/success', methods=['POST'])
def success():
if request.method == 'POST':
return render_template(r'home.html')
<form id = "login-form" action="{{ url_for('success') }}" method="post">
<div >
<input type="text" name="username" id="username" placeholder="Username">
</div>
<br>
<div >
<input type="password" id="password" name="password" placeholder="Password">
</div>
<br>
<div >
<button type="submit" id="login-form-submit">Sign In</button>
</div>
</form>
I hope this helps!