Flask does not direct to the home page - python

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 class="form-group">
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<br>
<div class="d-grid">
<button type="button" class="btn btn-primary btn-block" 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.

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 class="form-group">
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<br>
<div class="d-grid">
<button type="submit" class="btn btn-primary btn-block" id="login-form-submit">Sign In</button>
</div>
</form>
I hope this helps!

Related

Reset Password Using Django

I am trying to reset password using Django but I am getting the following error:
Method Not Allowed (POST): /reset/done/
Method Not Allowed: /reset/done/
Below are my forms:
Form Which Sent Link To My Email
<form action="{% url 'reset_pass' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" required autofocus>
</div>
<input type="submit" value="Send Email" class="btn btn-primary btn-block">
</form>
Form Which I Get On Clicking That Link
<form action="{% url 'password_reset_complete' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="password" class="form-control" name="new_pass" placeholder="New Password" required autofocus>
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_pass" placeholder="Confirm Password" required>
</div>
<input type="submit" value="Update Password" class="btn btn-primary btn-block">
</form>
URL
path('reset/pass/', views.reset_pass, name='reset_pass'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="feebeeapp/reset_form.html"), name='password_reset_form'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='feebeeapp/login.html'), name='password_reset_complete')
Not sure, what I am doing wrong. Can someone please guide me?
Your form is submitting to the wrong view. You are supposed to make a POST request to a PasswordResetConfirmView view.
If your PasswordResetConfirmView is thus registered as:
path('reset/', auth_views.PasswordResetView.as_view(), name='password_reset')
then in your form you work with:
<form action="{% url 'password_reset' %}" method="post">
…
</form>
Normally you already use this view to render the form. So you submit a POST request to the same view.
This view will send an email with a reset link, and then will redirect to the password_reset_complete view.

How to fix "Method not allowed" error in Python Flask app

I have a defined route in my Python Flask app(which worked fine).
#app.route('/insertpage', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
companyname = request.form['companyname']
username = request.form['username']
userpass = request.form['password']
new_company= Grocery(companyname=companyname,
username=username, userpass=userpass)
try:
db.session.add(new_company)
db.session.commit()
return render_template('index.html', data=Todos.query.all())
except:
return "The problem occurred while adding a new company...."
else:
groceries = Grocery.query.order_by(Grocery.created_at).all()
return render_template('index.html', groceries=groceries)
And I am collecting information in my HTML page:
<form action="/" method="POST">
<div class="form-row">
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New company:</label>
<input type="text" class="form-control" name="companyname" id="newStuff" placeholder="Enter name of new company">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New username:</label>
<input type="text" class="form-control" name="username" id="newStuff" placeholder="Enter username...">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New password:</label>
<input type="text" class="form-control" name="password" id="newStuff" placeholder="Enter password...">
</div>
<div class="col-sm-3 my-1">
<button type="submit" class="btn btn-primary btn-block">Add</button>
</div>
</div>
</form>
After a couple of successful CRUD operations, I am facing the following error(even if I defined 'POST' and 'GET' in my def).
Method Not Allowed
The method is not allowed for the requested URL.
The action attribute of your HTML form needs to match the name of your Flask route.
Your page is sending a POST to url '/' , so it isn't hitting your route, which is for the path '/insertpage'
You should change it to <form action="/insertpage" method="POST">

can't get the POST parameters in django

I am trying to make a login-page using django, I am facing troubles in getting POST parameters
login view:
def ProcLogin(request):
if request.method == 'POST':
account_name = request.POST.get('username','')
password = ToMd5(request.POST.get('password',''))
if not account_name or not password: return HttpResponse("invalid input")
template code:
<form method="post" action="{% url 'Main:login' %}" class="login_form">
{% csrf_token %}
<div class="form-group text-right">
<label for="username">User name:</label>
<input id="username" type="text" class="form-control box_shadow">
</div>
<div class="form-group text-right">
<label for="password">Password: </label>
<input id="password" type="password" class="form-control box_shadow">
</div>
<button type="submit" class="login_btn"></button>
</form>
Output when testing it:
invalid input
everything is supposed to be correct except the results aren't. Thank you.

400 Bad Request Flask

First of all, I've searched this error, tried everything those guys said but it won't work for me.
So, basically, I'm having a login form, and I can't even access the page as it gives me the 400 Bad Request error.
My flask code:
#app.route('/', methods=['POST', 'GET'])
def login():
users = mongo.db.users
login_user = users.find_one({'name' : request.form['username']})
if login_user:
if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == login_user['password'].encode('utf-8'):
session['username'] = request.form['username']
return redirect(url_for('index'))
return 'Invalid username/password combination'
My HTML form:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form method=POST action="{{ url_for('login') }}" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="pass" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary btn-block">Log In</button>
</form>
<br>
</div>
</div>
I have a similar register page but that works fine, it adds the user to the DB.
I have fixed it. I had to include if request.method == 'POST' under the login index. No idea how I didn't come to this earlier, it makes sense that I was requesting something from the form when I didn't even had the chance to type.
Thanks everyone.
Your html form should be render by login view because in your login view you are trying to get form value:
#app.route('/', methods=['POST', 'GET'])
def login():
...
return render_template('your_htmlform.html')
And now in your form action you can add action={{url_for('index')}} if form submitted.

make url semantic (dynamic) in Flask

I build a simple flusk service, this is a part of home page:
<form action="/results" method="POST">
<div>
<label class="required">Name: </label>
<input type="text" id="name" name="name" required="required"/>
</div>
<div>
<label class="required">ID: </label>
<input type="text" id="ID" name="ID" required="required"/>
</div>
<button type="submit" class="submit" id="submit" onclick="loading()"> Submit </button>
</form>
Here is a part of python:
#app.route('/', methods=['GET'])
def main_page():
return render_template('ui/home_page.html')
#app.route('/results', methods=['POST'])
def show_results():
# do something...
return render_template('ui/result_page.html')
It works when I click button and shows results in http://localhost:8080/results.
I now want to make the result url to be semantic base on users' input in the home page such as http://localhost:8080/results/user=balabala&ID=balabala. I tried modify the python
#app.route('/results/<url_postfix>', methods=['POST'])
def process_diff_by_platform(url_postfix):
# do something...
return render_template('ui/result_page.html')
but it shows 404 Not Found. I guess this is because that I hard coded the url in html template. But I have no idea how to fix that...
How do I solve this problem?
~ thanks

Categories

Resources