I wrote a small flask file:
myapp.py
#APP.route('/login', methods=['GET','POST'])
def login():
return flask.render_template('login.html')
#APP.route('/loginNext', methods=['POST','GET'])
def loginNext():
user=request.form.username
passw=request.form.password
return str(user)+str(pass)
login.html
<form id="foo" method="post" action="/loginNext">
Username : <input type="text" name='username' value="admin">
Password : <input type="password" name='password' value="">
<input type="submit" name="submit" value="Submit">
</form>
When I am trying to do request.form.username, I am getting
*AttributeError: 'ImmutableMultiDict' object has no attribute 'username' *
I read on stackoverflow as well as other places but didnot work. I tried doing request.form.get('username',None') that did not fetch the username.
<input type="text" name='username' value="admin"> was your input in .html file so to access in flask It is done in this way
username = request.form['username']
and you get the data as username .. same for password also.
if form tag contains below:-
<input type="text" name='username'>
In Flask Function, we can access it in 2 ways:-
username = request.form['username']
username = request.form.get('username')
Related
I created this form:
<html>
<body>
<div>
<form action="{{ url_for('login') }}" method="POST">
<div class="row">
<div>
<input id="email" name="email" type="email" class="validate">
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div>
<input id="password" type="password" name="password" class="validate">
<label for="password">Password</label>
</div>
</div>
<button type="submit" id="login" >Login</button>
<br>
</form>
<div>
</body>
</html>
and I have this Flask app that uses HTTPBasicAuth to do authentication.
#!flask/bin/python
from flask import Flask, jsonify, abort, request, make_response, url_for
from flask import render_template
from flask_httpauth import HTTPBasicAuth
#Needs: pip install flask-httpauth
app = Flask(__name__)
auth = HTTPBasicAuth()
#app.route('/', methods=['GET','POST'])
#auth.login_required
def login():
print('in login')
print(request.values.get('email'), request.values.get('password'))
templateToReturn = 'login.html'
if request.method == 'POST':
print('in post')
username = request.values.get('email')
password = request.values.get('password')
if verify_password(username, password):
print('password verified')
templateToReturn = 'index.html'
print('Curr user', auth.current_user())
print('request: ', request.method)
if request.method == 'GET' and auth.current_user():
templateToReturn = 'index.html'
return render_template(templateToReturn)
#app.route('/logout')
def logout():
return render_template('logout.html')
#auth.verify_password
def verify_password(email, password):
print('in verify pwd')
return verifyAuthentication(email, password)
def verifyAuthentication(email, password):
knownUsers = {'p1#gmail.com': 'pass',
'p2#yahoo.com': 'pass'}
authenticated = False
if email in knownUsers:
if knownUsers[email] == password:
authenticated = True
return authenticated
When I click the submit button of the form, I'm taken to the login() function. But isn't there supposed to be some way that it should go to the verify_password() function because it's decorated with #auth.verify_password?
How exactly and in which part of the code does the user authentication get registered with Flask? By which I mean: When does the #auth.login_required decorator actually allow their corresponding decorated functions to get executed?
Even the official page of HTTPBasicAuth() didn't explain this with an HTML example. Could someone please explain by adding to my code.
You forgot to add name attribute in your HTML input tag, so ideally it should be -
<input id="email" name="email" type="email" class="validate" />
<input id="password" name="password" type="password" class="validate" />
I have a web srv, and this is how i do my login
#app.route('/do_login', methods=['GET','POST'])
def do_login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
So, when i run the app and i try to login i receive the error "AttributeError: 'function' object has no attribute 'method'"
This is also my html page
<div class="row">
<form action="{{ url_for('do_login') }}" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="email" placeholder="exmple#ex.it">
<input type="password" name="password" placeholder="*****">
<input type="submit" value="Login">
<a class = "nav-link" href="/registrazione">Registrati</a>
</p>
</form>
</div>
Make sure you have the line from flask import request in the file
Make sure you did not redefine request anyway. Either you have explicitly defined another function called request
def request():
...
or you have assigned a function to request
request = some_random_method
I'm a newbie at programming and require your assistance -
In my python/flask routes.py script, I have a couple of app.routes. I would like to pass the name of the route to an html form action field, such that the values in the form are posted to the route of that name;
#app.route('/interfaceStats', methods=['GET', 'POST'])
def interfaceStats():
routeName='interfaceStats'
hostname = request.form['hostname']
username = request.form['username']
password = request.form['password']
command = ['python', 'readOperData.py', hostname, username,password]
print(command)
subIntObject = subprocess.check_output(command, shell=False)
intObjectInString = subIntObject.decode('ascii')
interfaceObjInJsonify = jsonify(intObjectInString)
interfaceObjInJson = json.loads(intObjectInString)
return render_template('interfaceStats.html', interfaceObjInJson=interfaceObjInJson, hostname=hostname)
<form id="submit-form" action={{routeName}} method="POST">
Hostname:
<input type="text", name="hostname" required>
Username:
<input type="text" name="username" required>
Password:
<input type="password" name="password" required>
<br>
<input type="submit" id="submit-form" class="hidden" />
</form>
Error:
the requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
192.168.254.1 - - [09/May/2019 15:49:56] "GET /method=%22POST%22?hostname=192.168.253.144&username=admin&password=password
HTTP/1.1" 404 -
You need quotes around your action attribute.
<form id="submit-form" action="{{routeName}}" method="POST">
I am trying to create my first website using Python + flask and am now having issues trying to add data to SQLite database using Flask-SQLAlchemy.
This is part where I am trying to add user to database but it fails:
#app.route('/register', methods=['GET','POST'])
def register():
if request.method == 'GET':
return render_template('registracija.html')
elif request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.Query(filter_by=username)
if user.count() == 0:
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
flash('You have registered the username {0}. Please login'.format(username))
return redirect(url_for('login'))
else:
flash('The username {0} is already in use. Please try a new username.'.format(username))
return redirect(url_for('register'))
else:
abort(405)
And my register.html page:
<form method="post" >
<div class="col-md-4">
Username: <br />
Password: <br />
Please repeat password: <br />
</div>
<div class="col-md-4">
<input type="text" name="username" /> <br />
<input type="password" name="password" /> <br />
<input type="password" name="repeatpassword" /> <br /> <br />
<input type="submit" name="register" value="Registruotis" />
</div>
</form>
When I fill form and press register button I get:
AttributeError: type object 'User' has no attribute 'Query'
Would be nice if someone could point me what I am doing wrong. I am running Python 3.5 On Windows 10.
user = User.Query(filter_by=username)
should be
user = User.query.filter_by(username=username).first()
All names in Python are case-sensitive: variable names, function names, class names, module names, exception names. If you can get it, set it, call it, construct it, import it, or raise it, it’s case-sensitive. Hence the error you are receiving about user not having any attribute 'Query' when it does have an attribute 'query'.
I recently got stuck with a pretty strange issue. I have a form in my template as follows:
<form class="form" id="loginForm" role="form" action="/user/login/"
method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email"
placeholder="Enter email" value="">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" placeholder="Password" value="">
</div>
<div class="cl-effect-7">
<button type="submit" class="btn btn-primary">SIGN IN</button>
</div>
</form>
I was getting CSRF token missing or incorrect. Digging further deep down i found that though csrftoken cookie is getting correctly set in the browser the POST request is having empty value of csrfmiddlewaretoken and hence it throws the error with the said reason.
Also here is my view(though I doubt if there is anything wrong with it)
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/user/')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/login.html', {},context_instance = context)
Here's the other view which redirects to login.html:
def index(request):
context_dict = {}
template = "user/login.html" #default template to render
user = None
user_profile = None
user = request.user.id
if user != None:
user_profile,created = UserProfile.objects.get_or_create(user=user)
#Check whether the user is new,if yes then he needs to select btw Mentor-Mentee
if user_profile and user_profile.is_new:
context_dict['selected'] = None
template = "user/select.html" #User has to select either Mentor/Mentee,so redirect to select.html
return render_to_response(template,context_dict,context_instance = RequestContext(request))
Now I used little JavaScript to get around this, by setting the value of csrfmiddlewaretoken from the cookie manually but that's a little strange behavior from Django.
PS: Im using Django 1.7 and tested this on all browsers.
Try adding this to your form:
<div style="display:none">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
</div>
Source: https://docs.djangoproject.com/en/dev/ref/csrf/#other-template-engines