Flask: how to send values by get method in temples? [duplicate] - python

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I have a html code such as:
<form action="/labeling?id={{id}}" method="get" target="hiddenFrame">
<input type="radio" name="options" value="x" onchange="this.form.submit()"> X<br>
<input type="radio" name="options" value="y" onchange="this.form.submit()"> y<br>
</form>
and the python code that gets the id of the element:
#app.route('/labeling', methods=['GET', 'POST'])
def labeling():
value = request.form['options']
d_id = request.form['id']
but it does not sent the values of id in the GET request? why?

Your id param is not form param, try:
d_id = request.args['id']
or better use id as method param:
<form action="{{ url_for('labeling', id=id) }}" method="POST" target="hiddenFrame">
<input type="radio" name="options" value="x" onchange="this.form.submit()"> X<br>
<input type="radio" name="options" value="y" onchange="this.form.submit()"> y<br>
</form>
#app.route('/labeling/<int:d_id>', methods=['GET', 'POST'])
def labeling(d_id):
value = request.form['options']

Related

FLASK - TypeError: 'ImmutableMultiDict' [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 1 year ago.
So I am doing a side project for my self, trying to learn.
Framework:
Flask
pandas
csv
raspberry 4
Goal:
to import a csv or xlsx file into a html form and print it out on the html page.
this is what I have so far:
when I import the file, I get the following.
TypeError: 'ImmutableMultiDict' object is not callable
Python Code:
def read_csv(filein):
filein = pd.read_excel('file.xlxs')
print(filein)
#app.route('/import_form', methods=['POST', 'GET'])
def import_form():
if request.method == "POST":
filein = request.files()
print(filein)
#return redirect('/thankyou.html')
else:
return 'something is wrong'
HMTL Code:
<form action="import_form" method="post" class="reveal-content">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<input name="filename" type="file" accept=".csv, .xlsx" class="form-control" id="filename" placeholder="filename" required >
</div>
</div>
<button type="submit" class="btn btn-default btn-lg">Send</button>
</div>
</form>
The error is because you can't use .files() files is not a function, so it isn't call able.
The right way to do that what you want is :
request.files["filename"]
You may visit here for more information.

how do take the user input with flask? [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 2 years ago.
I am working on a web GUI for a program I wrote the first thing a user of this software will access is the default login page for the program with that, said how do you take the username and password that the user-provided and validate it
how do you take the input from the user?
this is the login page in the flask script
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form['log'] == "Log In Here":
u_name = request.form['Uname']
pass_wrd = request.form['Pass']
else:
pass
print ( u_name , pass_wrd)
return
else:
return render_template('login-form.html')
this is the HTML side for the login page
<form id="login" method="get" action="login.php">
<label><b>User Name
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="Username">
<br><br>
<label><b>Password
</b>
</label>
<input type="Password" name="Pass" id="Pass" placeholder="Password">
<br><br>
<input type="button" name="log" id="log" value="Log In Here">
<br><br>
<input type="checkbox" id="check">
if request.form["log"] == "Log In Here
You have literally used the method here ^
request.form['name'] will get values from the input tag with name = 'name' (you can change that to catch the input values you want)
Store the value in variable and authorize the user with username and password from your database.

MultiValueDictKeyError at /admin/criminals 'gender' [duplicate]

This question already has answers here:
django MultiValueDictKeyError error, how do I deal with it
(9 answers)
Closed 3 years ago.
I sufering from the problem with my code, whenever i entered my data into the database and then at time when i click submit it will through an error Multyvaluekeyerror. i change my form value so many times but nothing is working. Please help me out this.....it very be thankfull.
MultiValueDictKeyError at /admin/criminals
'gender'
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/criminals
Django Version: 2.2.4
Exception Type: MultiValueDictKeyError
Exception Value:
'gender'
Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80
Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.4
Python Path:
['D:\\django project\\gadmin3',
'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\lenovo\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time: Mon, 7 Oct 2019 04:35:54 +0000
MAIN FORM CODE:-
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Gender</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div name="gender" id="" class="btn-group" data-toggle="buttons">
<label class="btn btn-default" data-toggle-class="btn-primary"
data-toggle-passive-class="btn-default">
<input type="radio" name="" value="male" data-parsley-
multiple="gender"> Male
</label>
<label class="btn btn-primary" data-toggle-class="btn-primary"
data-toggle-passive-class="btn-default">
<input type="radio" name="" value="female" data-parsley-
multiple="gender"> Female
</label>
</div>
</div>
</div>
VIEW SIDE CODE:-
def criminals(request):
if request.method=="POST":
cn = request.POST['crname']
ccrime = request.POST['crime']
cage = request.POST['age']
cheight=request.POST['height']
cbody = request.POST['bodymark']
crgen = request.POST['gender']
s= Criminals()
s.mname=cn
s.mcrime=ccrime
s.mage=cage
s.image = request.FILES['photo']
s.mheight=cheight
s.mbody=cbody
s.mgender=crgen
s.save()
messages.success(request,"Criminal Added Successfully.")
return render(request,'criminal.html')
else:
return render(request,'criminal.html')
Your inputs have name in them e.g
<input type="radio" name="" value="female" data-parsley-
This should be
<input type="radio" name="gender" value="female" data-parsley-
Your code can be futher refactored to:
def criminals(request):
if request.method=="POST":
s= Criminals(mname=request.POST['crname'],
ccrime=request.POST['crime'],
mage=request.POST['age'],
mheight= request.POST['height'],
mbody=request.POST['bodymark'],
mgender=request.POST['gender'])
s.save()
messages.success(request,"Criminal Added Successfully.")
return render(request,'criminal.html')
else:
return render(request,'criminal.html')
gender is a radio type button (also add the name in your form) and in case of not selected any option then you will not get any input.
To avoid this issue use the get method for extracting the value from POST request.
crgen = request.POST.get('gender', default_value)
This will eliminate the MultiValueDictKeyError issue

Upload file in flask with other form elements fails with 400 error

Getting a 400, when trying to upload a file ad send other form elements to flask from html. Tried to use ajax, but that throws me an error as well.
Python:
#app.route('/prod_diff_result', methods=['POST', 'GET'])
def prod_diff_result():
try:
host = request.form['host-prod-iterator']
print(host)
if request.files['file']:
f = request.files['file']
f.save(secure_filename(f.filename))
HTML:
<div class="main-div">
<form action="/prod_diff_result" method="POST" enctype="multipart/form-data">
<div class="grid-container">
<div class="grid-item">
<span class="label label-default ">PROD</span><br>
<p>Iterator Host : <input type="text" class="form-control" id="host-prod-iterator" value="10.47.7.57"
required></p>
<input type="radio" name="data_fetch_type" value="file" onclick="showfile()">Upload File
<input type="file" name="file" />
<input type="radio" name="data_fetch_type" value="db"> Get from DB
<input type="submit" />
</div>
</form>
</div>
I want to be able send hostname and file back to flask error in one request and using one form.
It gives an error because you try to access a form field that it cannot find, and assumes that somehow the request was bad, because it didn't include a required form field. You are trying to access:
host = request.form['host-prod-iterator']
However you have simply not given it a name in your HTML. If you give it a name, it should work:
<p>Iterator Host :
<input type="text" class="form-control" name="host-prod-iterator" id="host-prod-iterator" value="10.47.7.57" required>
</p>

Flask Bad Request Error; ocurring because of multiple POST requests [duplicate]

This question already has answers here:
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 4 years ago.
<form method = "POST">
<div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
<div class="box">
<input type="text" name="image-url" placeholder="Image URL Link"style="color:black" required="required" value = "new"/>
<textarea cols=80 rows=4 style="color:black" name = "description" placeholder="Place your description here" value = "new"></textarea>
<button type="submit">Upload</button>
</div>
</div>
</form>
{% for i in range(amount_of_images) %}
<div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
<div class="box">
<img src="{{image[i]}}" alt="view" width = "300" height = "300"/>
<form method = "POST">
<textarea cols=80 rows=4 style="color:black" name = "update-description" value = "update">{{description[i]}}</textarea>
<button type="submit">Update Description</button>
</form>
Above is my HTML/Jinja Code
#app.route("/gallery-manager", methods = ["GET", "POST"])
def gallery_manager():
if request.method == "POST":
if(request.form["image-url"] and request.form["description"]) is not None:
model.add_new_image(request.form["image-url"], request.form["description"])
id, image, description, amount_of_images = model.get_gallery()
return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)
if request.form['update-description'] is not None:
print("hello")
id, image, description, amount_of_images = model.get_gallery()
return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)
Above is my Python/Flask Code...
The issue, when I click on the update-description submit button, aka the second POST being handled in the html code, I get a 400 error
Bad Request
The browser (or proxy) sent a request that this server could not understand.
I realized that this error occurs when one of the POST fields are empty and can not be found. I understand that this happens because when I click the second POST submit button, it runs through the first POST check (request.form["image-url"] etc and finds that it is satisfied therefore wanting to run that code, but cant because update-description is still empty. How do I avoid this.
In other words how do I handle multiple POST methods.
Thank you,
This is because you are missing the action section in form where the form should send the request
<form action="/whereYouWantToSendRequest" method="post">
add your url endpoint by replacing this in the above
whereYouWantToSendRequest
here are the two request
<input type="text" name="image-url" value = "new"/>
<input type="text" name="update-description" value = "update"/>
and to figure out which request
if request.form["image-url"] == "new":
somethinggg
elif request.form["update-description"] =="update":
sommmm

Categories

Resources