Bad Request on POST form request with Flask [duplicate] - python

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Closed 4 years ago.
I'm using flask to make a login system and when I POST the form from the HTML form and I keep getting the following error: werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'username'.
I've looked up the error on Google and have gotten nowhere.
My HTML code is this:
<div class="card rounded-0" id="register_form">
<div class="card-header">
<h3 class="mb-0">Register</h3>
</div>
<div class="card-body">
<form class="form" role="form" method="POST" action="/auth/register" id="form">
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control form-control-lg rounded-0" id="email" required="">
<div class="invalid-feedback">Enter your Email.</div>
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control form-control-lg rounded-0" id="username" required="">
<div class="invalid-feedback">Enter your Username.</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control form-control-lg rounded-0" id="password" required="">
<div class="invalid-feedback">Enter your Password.</div>
</div>
<button type="submit" class="btn btn-success btn-lg float-right" id="btnLogin_regi">Register</button>
</form>
<p>Already have an account? </p><a class="btn btn-primary btn-lg" tabindex="-1" role="button" id="login_btn">Login</a>
</div>
</div>
My Python code is this:
#app.route('/auth/register', methods=["POST"])
def auth_post():
if request.method == "POST":
try:
q = database.query(User).filter(User.username == request.form.get("username"))
exists = database.query(q.exists()).scalar()
if exists:
return render_template("auth.html", error="User with same username/email exists.")
else:
username = str(request.form["username"])
password = str(request.form["password"])
email = str(request.form["email"])
print("Username: "+username+", Password: "+password+", Email: "+email)
temp = User(username=username, password=password, email=email)
database.add(temp)
database.commit()
except sqlalchemy.orm.exc.MultipleResultsFound:
return "Well this shouldn't be happening but it is. Join our Discord Server and tell one of the devs that the following error occured:\n<code>sqlalchemy.orm.exc.MultipleResultsFound (register)</code>"
I expect it to push the data to the SQLite Database, and once it does that, I will add more features after that.

The issue was that I didn't add name= to the input field.
Thanks #SuperShoot.

Related

How to pass bootstrap modal input data from HTML to Python Flask

I have a modal popup that allows users to input data. I want to pass that data to Flask so that I can put it in my database. For some reason, no data is being passed. I am printing out request.form and it logs "ImmutableMultiDict([])", when it should contain my form's inputs. I have been trying to use POST, but I'm open to other ideas. This is happening on Heroku, I haven't tested it locally.
HTML
<!-- Modal -->
<div class="modal fade" id="newProjectModal" tabindex="-1" aria-labelledby="newProjectModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="newProjectModalLabel">Create Project</h5>
<button type="button" class="btn-close" aria-label="Close"></button>
</div>
<form action="/createproject/" name="createProjectForm" id="createProjectForm" method="POST">
<div class="modal-body">
<div class="mb-3">
<label for="projectNameInput" class="form-label">Project Name</label>
<input type="text" class="form-control" id="projectNameInput" name="projectName" placeholder="New Project">
</div>
<div class="mb-3">
<label for="projectDescriptionInput" class="form-label">Project Description</label>
<textarea class="form-control" id="projectDescriptionInput" name="projectDescription" rows="3"></textarea>
</div>
<label for="selectUsersInput" class="form-label">Assign Personnel</label>
<select class="form-select" id="selectUsersInput" name="selectUsers" multiple aria-label="multiple select example">
{% for user in users %}
<option value="{{ user }}">{{ user }}</option>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary">Close</button>
<button class="btn btn-primary" type="submit" name="submit" value="Submit">Create Project</button>
</div>
</tr>
</form>
</div>
</div>
</div>
Python
#app.route('/createproject/', methods=['POST'])
def createproject():
if request.method == 'POST':
print(request.form)
project_name = request.form.get('projectName')
project_description = request.form.get('projectDescription')
return '''
<h1>The name value is: {}</h1>
<h1>The description value is: {}</h1>'''.format(project_name, project_description)
project_name and project_description are always "None" instead of the entered value

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">

HTML5 - Send message button not returning my function?

I'm brand new to coding and am following the Udemy Zero to Mastery course. I'm currently having trouble getting my HTML5 to process a function I've made in Python. I want to return my function, submit_form, when I click on 'send message'. Here's the HTML5:
<section id="three">
<h2>Get In Touch</h2>
<p>This is the contact section.</p>
<div class="row">
<div class="col-8 col-12-small">
<form method="post" action="index.html">
<div class="row gtr-uniform gtr-50">
<div class="col-6 col-12-xsmall"><input type="text" name="name" id="name"
placeholder="Name" /></div>
<div class="col-6 col-12-xsmall"><input type="email" name="email" id="email"
placeholder="Email" /></div>
<div class="col-12"><textarea name="message" id="message" placeholder="Message"
rows="4"></textarea></div>
</div>
</form>
<ul class="actions">
<!-- <button type="submit" class="btn btn-default btn-lg">Send Message</button> -->
<li><input type="button" value="Send Message" /></li>
</form>
</ul>
</div>
And here is my python function:
#app.route('/submit_form', methods=['POST', 'GET'])
def submit_form():
return 'form submitted!'
I'm having a lot of trouble understanding how to make the send message button return my function. Any help is much appreciated, thank you!

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.

Invalid Request Origin after Python post request

I've been trying to write a program which gets my school timetable which is locked behind a login screen, however when I run my python script I am greeted by:
Sorry, we are unable to complete this request
An error occured while submitting the form:
Invalid Request Origin
This is the code I've written so far:
import requests
login_url = 'https://WEBSITE/login?page=%2Fhomepage'
timetable_url = 'https://WEBSITE/timetable'
payload = {
'username': 'USERNAME',
'password': 'PASSWORD'
}
with requests.Session() as session:
post = session.post(login_url, data=payload, verify = True)
r = session.get(timetable_url)
print (post.text)
And this is the html from the login page:
<div id="content">
<form id="login" method="post" action="/login?page=%2Flogin%2F">
<input type="hidden" name="page" value="/login/" />
<div class="row collapse">
<div class="small-12 column">
<div class="logo">
<img src="/images/logo.php?logo=skin_logo_login&size=normal" alt="Schoolbox" />
</div>
</div>
<div class="small-12 column">
<p id="error-msg" class="alert-box alert"></p>
</div>
<div class="small-12 column">
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
</div>
</div>
<div class="row collapse">
<div class="small-12 column">
<p>Forgotten your password?</p>
</div>
<div class="small-12 column">
<input id="rememberme" type="checkbox" name="rememberme" value="1" />
<label for="rememberme">Remember me</label>
</div>
<div class="small-12 column login-links">
<input type="submit" name="Submit" value="Login" alt="Login" />
</div>
</div>
</form>
</div>
How exactly would I be able to solve this error, or would there be any other more viable solutions? Thank you.
This error Invalid Request Origin means that your origin does not match what is restricted by the server. You could try adding the Origin: header specifying your timetable_url, but it is likely that the page can only be called by another page on the server.

Categories

Resources