Problem in getting data from form in flask - python

I am basically creating a flask web app which takes username from user and gets his /her codeforces data I am having a problem in extracting the email-id
from the form. I am getting the username but not the email-id.They are both in one form tag in the html file.
Error in browser:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'email-id'
<form method="POST">
<div class="field">
<label class="label">Username:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter Codeforces username" name="username" value="{{user.handle}}"></input>
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-info" type="submit" value="Get Info">
</div>
<div class="field">
<label class="label">EMail id:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter mail id" name="email-id" value="">
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-mail" type="submit" value="Get Mail">
</div>
</form>
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
username = request.form['username']
email_id = request.form['email-id']
print(email_id)
print(username)

Related

2 form at the same page flask

Hello guys hope u doing fine, I got this project and in home page of my website i have two form
1 to login and the other to upload a file however every time i submit with any form the same function keeps getting executed please help.
this is the html code
<!--login-->
<section class="bg-dark text-light p-5 text-center">
<div class="container">
<h2>First step </h2>
<form action = "http://localhost:5000" method="post" name="login" >
<div class="col">
<div class="hide-md-lg">
<h4>Sign in to your <span class="text-warning">Linkedin account</span> </h4>
</div>
<br>
<input type="text" name="username" placeholder="Username" required>
<br><br>
<input type="password" name="password" placeholder="Password" required>
<br><br>
<input class="btn btn-primary" type="submit" value="Login">
</div>
</form>
</div>
</section>
<!--upload excel-->
<section class="bg-dark text-light p-4">
<div class="container bg-primary rounded border-0 p-5">
<div class="d-md-flex justify-content-between align-items-center">
<div class="container">
<h5 class="mt-2">Choose an excel file</h5>
<h6 class="mb-3"><span class="text-warning">NB: first 2 columns have to be: "Prénom" and "Nom"</span></h6>
</div>
<form class="input-group" action = "http://localhost:5000" method = "POST" enctype = "multipart/form-data" name="upload">
<input class="form-control size-file" type="file" name="file" id="formFile">
<input class="btn btn-dark" type = "submit" value="Start scraping" >
</form>
</div>
</div>
</section>
and this is the backend part
#app.route('/', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST' :
f = request.files['file']
f.save(secure_filename(f.filename))
df = pd.read_excel(f.filename)...............
#app.route('/', methods = ['GET', 'POST'])
def login_info():
if request.method == 'POST' and 'Sign in to your' in request.form['h4']:
user_info = request.form.get("username")
pass_info = request.form.get("password")
Although unable to try it this way, I updated your code with different action parameters.
<!--login-->
<section class="bg-dark text-light p-5 text-center">
<div class="container">
<h2>First step </h2>
<form action = "{{url_for('login_info')}}" method="post" name="login" >
<div class="col">
<div class="hide-md-lg">
<h4>Sign in to your <span class="text-warning">Linkedin account</span> </h4>
</div>
<br>
<input type="text" name="username" placeholder="Username" required>
<br><br>
<input type="password" name="password" placeholder="Password" required>
<br><br>
<input class="btn btn-primary" type="submit" value="Login">
</div>
</form>
</div>
</section>
<!--upload excel-->
<section class="bg-dark text-light p-4">
<div class="container bg-primary rounded border-0 p-5">
<div class="d-md-flex justify-content-between align-items-center">
<div class="container">
<h5 class="mt-2">Choose an excel file</h5>
<h6 class="mb-3"><span class="text-warning">NB: first 2 columns have to be: "Prénom" and "Nom"</span></h6>
</div>
<form class="input-group" action = "{{url_for('upload_file')}}" method = "POST" enctype = "multipart/form-data" name="upload">
<input class="form-control size-file" type="file" name="file" id="formFile">
<input class="btn btn-dark" type = "submit" value="Start scraping" >
</form>
</div>
</div>
</section>
And the #app.route should lead to two function :
#app.route('/upload_file', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST' :
f = request.files['file']
f.save(secure_filename(f.filename))
df = pd.read_excel(f.filename)...............
#app.route('/login_info', methods = ['GET', 'POST'])
def login_info():
if request.method == 'POST' and 'Sign in to your' in request.form['h4']:
user_info = request.form.get("username")
pass_info = request.form.get("password")
If you want both those page to return to your home screen, you just have to tell them to return to this same template with render_template() or redirect()

POST request to Flask Blueprint api not working

I am trying to execute a form POST request. The request is received at the route api function but the POST condition is not executing.
Code
<form class="pt-2 pb-4" action = "{{ url_for('data_sources_api.testfn') }}" method = "POST">
<div class="row">
<div class="col-md-4 mb-3">
<label for="url" class="form-label">URL</label>
<input type="text" class="form-control" id="url" name="url" aria-describedby="emailHeurllp"
placeholder="Enter new events top domain source url">
</div>
<div class="col-md-4 mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Organization Name">
</div>
<div class="col-md-12">
<button type="button" class="btn btn-secondary mr-2" value="submit" name = "submit">Submit</button>
</div>
</div>
</form>
Flask Code
#data_sources_api.route('/login/test', methods=["GET", "POST"])
def testfn():
# Check if user is loggedin
if loggedin():
# User is loggedin, render the home page
if request.method == 'POST':
print("POST Request Received")
result = request.form
return render_template('users/data-sources.html', role=session['role'])
return redirect(url_for('account_api.login'))
The request received is GET when i click the submit button and not POST :(
Thanks in advance
I think the problem is with button. Replace the button with input type="submit":
<input type="submit" value="Submit">
Here is the example of Django form.

Update the password if the user has forgotten while Login-in, Python Flask

I am trying to update the password if the user has forgotten while Login-in. But continuously it is giving the same error given below.
Bad Request: The browser (or proxy) sent a request that this server could not understand.
app.py
#app.route('/NewPassword', methods=['POST', 'GET'])
def NewPassword():
if request.method == 'POST':
OldEmail = request.form['NewPswdInputEmail']
OldPhone = request.form['NewPswdInputPhoneNo']
NewPaswd = request.form['NewPaswdInputPassword']
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("UPDATE USERS SET Paswd='" + NewPaswd + "' WHERE Email ='" + OldEmail + "' OR Phone ='" + OldPhone + "'")
cur.connection.commit()
return "Password Updated"
return render_template('NewPassword.html')
NewPassword.html
<form action="/NewPassword" method="post" oninput='NewPaswdConPassword.setCustomValidity(NewPaswdConPassword.value != NewPaswdInputPassword.value ? "Password does not match." : "")'>
<div class="form-group">
<label for="customRadio">Select Option to Change Password Between Email & Phone No.</label>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="customRadioInline1" name="customRadioInline" value="Email" class="custom-control-input" checked>
<label class="custom-control-label" for="customRadioInline1">Email Id</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="customRadioInline2" name="customRadioInline" value="Phone" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Phone No.</label>
</div>
</div>
<div class="form-group" id="EmailShowHide">
<label for="NewPswdInputEmail">Email Address</label>
<input type="email" class="form-control" name="loginInputEmail" id="NewPswdInputEmail" aria-describedby="emailHelp" placeholder="Email address">
<small id="loginemailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group" id="PhoneShowHide" style="display: none">
<label for="NewPswdInputPhoneNo">Phone Number</label>
<input type="tel" id="NewPswdInputPhoneNo" name="NewPswdInputPhoneNo" class="form-control" pattern="[0-9]{4}[0-9]{2}[0-9]{4}" placeholder="Phone number">
<small id="NewPswdPhoneHelpInline" class="text-muted">Enter Valid Number</small>
</div>
<div class="form-group">
<div class="tool">
<label for="NewPaswdInputPassword">New Password</label>
<div class="input-group" id="NewPaswdShowHide">
<input type="password" class="form-control" name="NewPaswdInputPassword" id="NewPaswdInputPassword" pattern="^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,20}$" placeholder="New password" required>
<div class="input-group-append">
<a class="btn btn-primary">
<i class="bi bi-eye-slash" aria-hidden="true"></i>
</a>
</div>
</div>
<span class="tooltext">Password Must be Alphanumeric with atleast an UpperCase & LowerCase Characters</span>
<small id="NewPaswdHelpInline" class="text-muted">Must be 8-20 characters long.</small>
</div>
</div>
<div class="form-group">
<label for="NewPaswdInputConPassword">Confirm New Password</label>
<input type="password" class="form-control" name="NewPaswdConPassword" id="NewPaswdInputConPassword" placeholder="Confirm new password" required>
</div>
<button type="submit" name="Login" id="NewPaswdSubmit" class="btn btn-primary">Submit</button>
</form>
I am trying to do is, if my database "USERS" has Email or Phone no. then Paswd will get updated with the new password which is input by the user
Please tell me what I am doing wrong.
I assume you are using Flask. Is your application running in debug mode?
Running the application in debug mode can help identify where the issue is.
The issue is with the email HTML form input. When you submit a form, the data is sent as key=value pairs, in this case you are using Flask so it is a python dictionary. So in the /NewPassword route, when you request request.form['NewPswdInputEmail'], you are grabbing a value in that dictionary submitted from the form with 'NewPswdInputEmail' as a key.
In the form input the key is the name attribute.
That's why you get the KeyError because the name in the email input form has name="loginInputEmail" instead of name="NewPswdInputEmail"
All you need to do is rename loginInputEmail attribute in the email input field to NewPswdInputEmail.

How to post data via form HTML?

I want to post the data to the server via form. How can I do this?
<div class="panel-body">
<form role="form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sender-email" class="control-label">Username:</label>
<div class="input-icon"> <i class="icon-user fa"></i>
<input id="sender-email" type="text" placeholder="Username" class="form-control email">
</div>
</div>
<div class="form-group">
<label for="user-pass" class="control-label">Password:</label>
<div class="input-icon"> <i class="icon-lock fa"></i>
<input type="password" class="form-control" placeholder="Password" id="user-pass">
</div>
</div>
<div class="form-group">
<input class="btn btn-primary btn-block" id="authenticate_user" type="submit" value="Submit">
</div>
</form>
</div>
My views.py
#csrf_exempt
def signin(request):
if request.method == 'POST':
print request.POST.get('sender-email') #prints None
username = request.POST['username'] # throws error, username not available.
password = request.POST['password']
How do I post the data without using jquery? I know of a way of posting through AJAX jquery, but dont wanna do that.
The 'name' attribute of input tags is set as keys of request.GET and request.POST.
Add name attribute to all your input tags.
<input name="username" id="sender-email" type="text" placeholder="Username" class="form-control email">
<input name="password" type="password" class="form-control" placeholder="Password" id="user-pass" >
POST data are populated using the name attribute of your input elements. Change your id attributes or add a name one accordingly. E.g:
<input type="password" class="form-control" placeholder="Password" name="user-pass">
You should also consider using a form to handle your data more easily.

User does not exist when I logs in django

I want to make my own site to log in django 1.7.
But when I get logs will be taken to a page to sign in and get a message that there is no such user. My user is in the database.
VIEW
def my_login(request):
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
print "User does not exist"
return render_to_response('tests/login1.html', context_instance=RequestContext(request))
TEMPLATE
<form class="form-horizontal" name="LoginForm" action="./" method="post">
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" value="" placeholder="Username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" name="password" value="" id="password" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Login</button>
</div>
</div>
</form>
You are not sending the username to the view because the name attribute is missing in your input tag. Instead of:
<input type="text" id="username" value="" placeholder="Username">
try this:
<input type="text" name="username" id="username" value="" placeholder="Username">

Categories