Flask isn't getting the checkbox value - python

I am trying to print off the checkbox value in Flask when I hit the submit button.
app.py snippet:
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.args.get('check'))
return render_template('test.html')
HTML:
<div class="container"><br>
<form role="form" method="post">
<input type="checkbox" name="check" value="test">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
It returns 'None' when I hit the submit button.
I have also tried request.form.get()
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.form.get('check'))
return render_template('test.html')
That also returns 'None'.

When submitting an HTML form, unchecked checkboxes do not send any data. On Flask's side, there will not be a key in form, since no value was received. If you want to check if a single checkbox (with a unique name) is checked, just test if it's name is in form. If you want to check which of multiple checkboxes (with the same name, but different values) are checked, use getlist instead.
One boolean:
<input type="checkbox" name="check">
checked = 'check' in request.form
Multiple options:
<input type="checkbox" name="check" value="1">
<input type="checkbox" name="check" value="2">
<input type="checkbox" name="check" value="3">
selected = request.form.getlist('check')
any_selected = bool(selected)

Related

How do I in Flask get what of two buttons in same form has been clicked to perform different actions?

I have a single input field where I wan't 2 buttons with different actions.
<!-- Search box -->
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="UserID" name="search"
aria-describedby="useridHelp" required pattern="[0-9]{5,7}">
<!-- Submit/Update button -->
<button id="add-update" type="button" class="btn btn-primary mb-2 mr-2">Add/Update</button>
<!-- Remove button -->
<button id="remove" type="button" class="btn btn-primary mb-2">Remove</button>
If I make the "add-update" button to a type="submit" and use if request.method == 'POST': in Flask then I Submit the value of the field. Great.
But how do I call the "remove" button into Flask so I can give it a function?
In other words. When a user click the "Add/Update button" the field input should be added to my database. When a user click the "Remove" button the field input should be deleted from my database.
How do I grab which button has been clicked in Flask?
I found the solution here: https://predictivehacks.com/?all-tips=how-to-add-action-buttons-in-flask
The answer is to do:
if request.form.get('action1') == 'VALUE1':
The example is:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.form.get('action1') == 'VALUE1':
pass # do something
elif request.form.get('action2') == 'VALUE2':
pass # do something else
else:
pass # unknown
elif request.method == 'GET':
return render_template('index.html', form=form)
return render_template("index.html")
<h3>Our Flask Buttons<h3/>
<form method="post" action="/">
<input type="submit" value="VALUE1" name="action1"/>
<input type="submit" value="VALUE2" name="action2" />
</form>
HTML Change:
You can have a form, with one text box and two buttons. The button names are the same(two_buttons) and will have different values(add-update and remove, which will be used in the flask to identify them.
two_button_add_and_remove.html
<form action="{{ url_for('check_button')}}" method="POST">
<!-- Search box -->
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="UserID" name="search"
aria-describedby="useridHelp" required pattern="[0-9]{5,7}">
<!-- Submit/Update button -->
<button name="two_buttons" value="add-update" id="add-update" type="submit" class="btn btn-primary mb-2 mr-2">Add/Update</button>
<!-- Remove button -->
<button name="two_buttons" value="remove" id="remove" type="submit" class="btn btn-primary mb-2">Remove</button>
</form>
Now in Flask, check the value of request.form['two_buttons'] and based on it call your add or remove function with parameter request.form['search']
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/check_button', methods=['GET','POST'])
def check_button():
print("Request.method:", request.method)
try:
if request.form['two_buttons'] == "add-update": # check if value is "add-update"
print(f"call add-update_function with {request.form['search']}")
else:
print(f"call remove_function with {request.form['search']}")
return render_template('two_button_add_and_remove.html')
except Exception as e:
return render_template('two_button_add_and_remove.html')
if __name__ == '__main__':
app.run(debug=True)

how to write a single view for 2 forms like signup and login in one html file

i have html file that contains both login and signup form
<form method = "POST" enctype="multipart/form-data" >
{{ user_form.as_p }}
{% csrf_token %}
<input type="text" id="firstname" placeholder="First Name" name = "first_name" required>
<div class="invalid-feedback">Please enter a valid first name.</div>
<input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required>
<div class="invalid-feedback">Please enter a valid last name.</div>
</form>
and a similar login form
how to write a single view for both of these forms using buttons
i have already seen How can I build multiple submit buttons django form? this but i didn't found useful
def user_login:
if request.method == 'POST' and request.POST.get('submit') == 'name1':
pass
elif request.method == 'POST' and request.POST.get('submit') == 'name2':
pass
in this how to write else code if request.method not POST for every form

flask/jinja2: form textinput set value

How do I set the VALUE attribut of a text input field (HTML forms).
I tried it with:
Python:
#app.route("/function_a", methods=['GET', 'POST'])
def function_a():
form = ReusableForm(request.form)
query = "test value"
if request.method == 'POST':
name=request.form['name']
return render_template('zeit.html', form=form, query_test=query)
HTML template:
{{ form.name(value="{{ query_test }}") }}
the website output is like:
<input id="name" name="name" required type="text" value="{{query_test}}">
expected website output:
<input id="name" name="name" required type="text" value="test value">
I got the solution:
in the HTML template I wrote only the variable without the brackets.
{{ form.name(value=query_test) }}
and the output is like I want it:
<input id="name" name="name" required type="text" value="test value">

Django check if checkbox is selected

I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
Currently I am stuck on refining the search using checkboxes, radio buttons etc
The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as such:
views.py
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True;
elif len(q) > 22:
error = True;
else:
sequence = Targets.objects.filter(gene__icontains=q)
request.session[key] = pickle.dumps(sequence.query)
return render(request, 'result.html', {'sequence' : sequence, 'query' : q, 'error' : False})
return render(request, 'search.html', {'error': True})
search.html
<p>This is a test site</p></center>
<hr>
<center>
{% if error == true %}
<p><font color="red">Please enter a valid search term</p>
{% endif %}
<form action="" method="get">
<input type="text" name="q">
<input type="submit" value="Search"><br>
</form>
<form action="" method="post">
<input type='radio' name='locationbox' id='l_box1'> Display Location
<input type='radio' name='displaybox' id='d_box2'> Display Direction
</form>
</center>
My current idea is that I check which checkboxes/radio buttons are selected and depending which are, the right data will be queried and displayed in a table.
So specifically:
How do I check if specific check-boxes are checked? and how do I pass this information onto views.py
Radio Buttons:
In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:
<form action="" method="post">
<label for="l_box1"><input type="radio" name="display_type" value="locationbox" id="l_box1">Display Location</label>
<label for="d_box2"><input type="radio" name="display_type" value="displaybox" id="d_box2"> Display Direction</label>
</form>
Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:
# views.py
def my_view(request):
...
if request.method == "POST":
display_type = request.POST.get("display_type", None)
if display_type in ["locationbox", "displaybox"]:
# Handle whichever was selected here
# But, this is not the best way to do it. See below...
That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:
forms.py:
from django import forms
DISPLAY_CHOICES = (
("locationbox", "Display Location"),
("displaybox", "Display Direction")
)
class MyForm(forms.Form):
display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)
your_template.html:
<form action="" method="post">
{# This will display the radio button HTML for you #}
{{ form.as_p }}
{# You'll need a submit button or similar here to actually send the form #}
</form>
views.py:
from .forms import MyForm
from django.shortcuts import render
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
# Have Django validate the form for you
if form.is_valid():
# The "display_type" key is now guaranteed to exist and
# guaranteed to be "displaybox" or "locationbox"
display_type = request.POST["display_type"]
...
# This will display the blank form for a GET request
# or show the errors on a POSTed form that was invalid
return render(request, 'your_template.html', {'form': form})
Checkboxes:
Checkboxes work like this:
forms.py:
class MyForm(forms.Form):
# For BooleanFields, required=False means that Django's validation
# will accept a checked or unchecked value, while required=True
# will validate that the user MUST check the box.
something_truthy = forms.BooleanField(required=False)
views.py:
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
...
if request.POST["something_truthy"]:
# Checkbox was checked
...
Further reading:
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield
https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield
In models :
class Tag:
published = BooleanField()
(...)
In the template:
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').
For example :
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />
Say if 1,4 were checked,
check_values = request.POST.getlist('tag')
check_values will contain [1,4] (those values that were checked)
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value=""
{% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

Flask form submitting error

I have a form like this:
<form method="post" action="/addReceiverHandler" id="addReceiverForm">
<label for="title">name:</label>
<input type="text" name="title" value="name"/><br>
<label for="dimmer">Dimmer:</label>
<input type="text" name="dimmer" value="True"/><br>
<input type="submit" value="sync" />
</form>
And I recive the answer with:
#app.route('/addReceiverHandler', methods=['POST', 'GET'])
def addReceiverHandler():
if request.method == 'POST':
print request.form
But the strange thing is that the input field "title" arrives with value "name" but that's it. The second input does not arrive, why is that?
Never mind! Stupid hidden jQuery.
I had set a preventDefault behaviour in jQuery and submitting that way, seems like I've forgotten that...

Categories

Resources