This is the Html form:
<form action='use.py'>
<div><input type='text' name='etc'></div>
<p><input type='submit' value='etc!'></p>
</form>
And this is the python for it
colour = form["colour"].value
The top html form is a text box that users can type something in.
If I were to have a drop down box / radio button form like this:
<form action='etc.py'>
<p>List Type:</p>
<div><input type='radio' name='status' value='bulleted' checked>
Bulleted
</div>
<div><input type='radio' name='status' value='numbered'>
Numbered
</div>
<p>Text style:</p>
<div><input type='checkbox' name='bold'>
<b>Bold</b>
</div>
<div><input type='checkbox' name='italic'>
<i>Italic</i>
</div>
<p>Movies to display:</p>
<div>
<select name='type'>
<option>Only numbers</option>
<option>Only names</option>
</select>
</div>
<p><input type='submit' value='Display'></p>
</form>
How would I write my python? Like this?
only_numbers = form["Only numbers"].value
You can write a Python CGI script, but most Python frameworks are built upon WSGI and have a concept of request/response objects. For example, in Django the value would be available at request.POST['fieldname'].
Using the python CGI module, it is like:
form = cgi.FieldStorage()
# for multiple elements with same name or elements with multiple values
a_list = form.getlist("multiple_select_input")
# For single value elements
if "single_value_input" in form:
x = form["single_value_input"].value
else:
x = "default value"
# or
x = form.getvalue("single_value_input", "default value")
Related
I am working with dynamic data that requires an ID and a year to load, both of which are input by the user. The ID is unique, so two users will very likely be looking at different data. They are passed into a URL that returns a large dictionary. This dictionary is then passed to a bunch of other functions for various analyses and visuals. I was thinking of displaying the data in its own hidden route and have other routes call on it (I am new to flask, so there could be a better/more efficient way of storing and accessing dynamic data like this).
Here is the flask code to display the form and where I try to access the data:
#app.route("/")
def home():
return render_template("index.html")
#app.route("/data/<lid>/<ssn>", methods=["GET","POST"])
def data_league():
if request.method == "POST":
league_id = request.form["lid"]
season = request.form["ssn"]
url = 'http://fantasy.espn.com/apis/v3/games/ffl/seasons/' + season + '/segments/0/leagues/' + league_id + '?view=mMatchupScore&view=mTeam&view=mSettings'
r = requests.get(url,
params={'view':'mMatchup'})
d = r.json()
return d
And the HTML code that creates the form:
<form class="row row-cols-lg-auto g-3 align-items-center" action="#" method="post" style="margin-
left: 180px;">
<div class="col-5">
<label class="visually-hidden" for="league_id">Username</label>
<div class="input-group">
<input type="text" class="form-control" name="lid" id="lId" placeholder="League ID">
</div>
</div>
<div class="col-5">
<label class="visually-hidden" for="season">Preference</label>
<select class="form-select" name="ssn" id="Ssn">
<option selected>Select a Season</option>
<option value="1">2020</option>
<option value="2">2019</option>
<option value="3">2018</option>
</select>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
When I run the app and input an ID and year, I get a TypeError saying that "data_league() got an unexpected keyword argument 'lid'". What am I doing wrong?
I'm using Django 1.8 and python 2.7
In my template I have a radio button.
<div class="form-group">
<label class="col-md-4 control-label" for="radios">Liquids:</label>
<div class="col-md-4">
<label class="radio-inline" for="radios">
<input type="radio" name="liquids" id="liquids" value="1" disabled>
With cough
</label>
<label class="radio-inline" for="radios">
<input type="radio" name="liquids" id="liquids" value="0" >
No cough
</label>
</div>
</div>
When I push the submit button whatever is my choice, the first option is taken as selected. Do you know how to fix this?
How do I get the correct value of radio choice in views.py?
Also, when I render the template having filled values with selected the 2nd option, the radio button for the first option is selected in template.
Can you provide your complete HTML page? Probably you forgot to use <form></form> HTML tag.
When you need to get the selected values of an input element you can use jQuery. The function .serializeArray(); will come in handy.
var fields = $( ":input" ).serializeArray();
I tried to used bootstrap-select whith the following example, but in Flask I get only one value and not the maximum two values?
<form class="form-horizontal" action="{{url_for('compare')}}" method="get" role="form">
<div class="input-group">
<span class="input-group-addon">Tests:</span>
<select name='tests' class="selectpicker show-menu-arrow form-control" multiple data-max-options="2" data-live-search="true">
<option value="Test1">Test1</option>
<option value="Test2">Test2</option>
<option value="Test3">Test3</option>
</select>
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Search!</button>
</span>
</div>
</form>
<hr>
The route in Flask is define like below:
#app.route("/compare/", methods=["GET"])
#templated('compare.tmpl')
def compare():
tests = request.args.get('tests')
How is it possible to get maximum two selected values in flask e.g. Test1 and Test2?
request.args is a MultiDict. It provides a method called getlist that will return a list of items for the given key rather than a single value. Update your code to the following.
tests = request.args.getlist('tests')
More information can be found in the werkzeug documentation.
My goal is to run python function when a user clicks on a button within a form on my web page, when the argument is taken from textarea HTML element.
The following html code is my form with button within and is part of django application.
<div id="contact_form" class="col_400 float_l">
<form id="demoForm" name="contact" >
<label for="text">Your Review:</label>
<textarea id="text" name="text" rows="0" cols="0" class="required"></textarea>
<div class="cleaner_h10"></div>
<input type="button" onclick="return Button1_onclick()" class="submit_btn float_l" name="submit" id="predictSentBtn" value="Predict" />
</form>
</div>
I looked on django.forms and django.forms.widgets, but still don't understand how to "link" between existing html elements and python objects.
This should help:
<div id="contact_form" class="col_400 float_l">
<form id="demoForm" name="contact" >
<label for="text">Your Review:</label>
<textarea id="needid" name="needid" rows="0" cols="0" class="required"></textarea>
<div class="cleaner_h10"></div>
<input type="button" onclick="return Button1_onclick()" class="submit_btn float_l" name="submit" id="predictSentBtn" value="Predict" />
</form>
def function(request):
if request.method = 'POST':
print request.POST['needid'] # print request.POST.get('needid')
Try it ;)
I have a form with generic fields
forms.py
class OfferForm(forms.ModelForm):
class Meta:
model=Offer
some_views.py
def add_field(request):
form = OfferForm()
#some logic here
for x in list:
form.fields[x]=forms.ModelChoiceField(queryset=some_query)
return render_to_response(template,{'form':form,'list_of_add_field':list}
So , In my template i want to do something like this:
{%for x in list_of_add_field%}
Name add field is {{x}}
Choices:
{%for y in form.{{x}}.choices %}
<input type="checkbox" name="form.{{x}}.html_name">y </input>
{%endfor%}
{%endfor%}
How can do that ? Any idea ?
Thank you !
I see you are intended to do and here my reply. You should adapt your code to django and not django to your code. In this way, to solve your issue, the 'prefix' form resource is the right option:
You can put several Django forms inside one tag. To give each Form its own namespace, use the prefix keyword argument:
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print mother.as_ul()
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
>>> print father.as_ul()
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
In your case, you can make a new form for each X of your list. Put all new forms in a list named formset. Then, in your template, you should write form loop:
{{for form in formset}}
... Here your code for a form ....