I am new at this and trying to submit a basic form which has a dropdown list and 2 text fields. The lists value is the path of the flask route which needs to be submitted the data.
Depending on the item the user selects from the list, i would like to submit the form with data to that url, eg if user selects "a" then i would like to submit form to http://url/url1. How can this be done?
<form action="" class="form1" method="get">
<select class="form-control" id="function" name="cars">
<option value="/url1">a</option>
<option value="/url2">b</option>
<option value="/url3">c</option>
</select>
<input class="form-control" type="number" name="number1" value="">
<input class="form-control" type="number" name="number2" value="">
<input class="form-control" type="submit">
</form>
I have python flask code on server :
#app.route("/url1")
def url1():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
#app.route("/url2")
def url2():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
if i understand your question , you can solve it by jquery
code sample
$("#function").change(function() {
var action = $(this).val();
$("#form1").attr("action",action);
});
or
you can set a default action for the form and then in route do according to the selected value
I used redirection in app.py to resolve this
<form action="/submit" class="form1" method="get">
and then
#app.route('/submit', methods=['GET'] )
def submit():
num=request.args.get('number1',default=-1, type=int)
return redirect(url_for('url1', m=num))
#app.route("/url1")
def url1():
evaluate the numbers and return render_template()
Related
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">
First of all sorry if that's a silly question, but I am kind of stuck..
I want to pass a couple of variables from my HTML/Bootstrap page to Flask. The variables are obtained in a form.
The variable is to be selected from a dropdown. Once the variable is selected from mySQL2 it should be stored in customername.
At the moment I've got this sample code which does not work at all.
<form action="" class="form-group" method="post">
<div class="form-group">
<label for="selectcustomer">Select your customer</label>
<input
<select class="form-control" id="selectcustomer">
{% for j in mySQL2 %}
<option>{{j[2]}}</option>
{% endfor %}
</select> value="{{request.form.customername}}">
<input type="text" class="form-control" name="customername" value="{{request.form.customername}}">
</div>
<br>
<input class="btn btn-default" type="submit" value="Submit">
</form>
How can I post the selected value into customername?
The form looks like this:
I need the selection field to be a dropdown. Once a value is selected it should be stored in customername.
Before form submission can't get the submit values. To get posted data in view use:
request.form["selectcustomer"]
note: html select tag should have a name attribute <select name="selectcustomer" ...> so you can get value with name not the select id.
Lets say you have a view as follows:
def customer():
customername = ""
if request.method == 'POST':
customername = request.form["customername"]
return render_template("yourhtmlfile", customername=customername)
#yourhtml
...
{{customername}}
I'm diving into Flask for the first time and I'm having some trouble getting something work.
I currently have a template for when my tab values is empty, it contains a form that when submitted should call a specific function using the parameters of the form and return another template. Each call of the form should in, fact call the index.html template with different values.
Relevant parts of code are as follows:
main.py
#app.route('/', methods=['POST','GET'])
def main():
global maxDepth, numberOfRelated
if not values:
return render_template('initial.html')
if request.method=='POST':
url = request.form['url']
maxDepth = request.form['depth']
numberOfRelated = request.form['numberOfRelated']
values = crawling(url,maxDepth,numberOfRelated)
return render_template('index.html',var=values)
The form part of initial.html and index.html are actually the same
<form class="form-inline" action="/" method="POST">
<div class="form-group">
<input name='url' type="text" class="form-control"/>
</div>
<div class="form-group minorForm">
<input name='numberOfRelated' type="text" class="form-control" />
</div>
<div class="form-group minorForm">
<input name='depth' type="text" class="form-control" />
</div>
<div class="form-group navbar-right">
<button class="btn btn-success minorForm generate" type="submit"> Generate</button>
</div>
</form>
In your main method, unless values is global, it won't be defined for if not values.
As to your question, add another render_template call just after the conditional for if the form was submitted:
if request.method=='POST':
url = request.form['url']
maxDepth = request.form['depth']
numberOfRelated = request.form['numberOfRelated']
values = crawling(url,maxDepth,numberOfRelated)
return render_template('index.html',var=values) # 1
return render_template('index.html',var=values) # 2
If the form is submitted, the conditional will be true and the template will be rendered at comment #1. If the user is navigating to the page normally, the conditional will be false and the line with comment #2 will be called.
I'm a bit confused about the question, but you should always redirect after a POST (unless there was an error in the form and no action was taken). That way the same action won't be repeated if the user reloads the page.
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...
I am trying to validate fields, one visible filled by the user, and an other one: hidden for the user but filled by the template.
Here is my form:
class AForm(forms.Form):
xxxx = forms.CharField(max_length=30)
yyyy = forms.CharField(max_length=30,widget=forms.HiddenInput)
def clean(self):
xxxx=self.cleaned_data['xxxx']
yyyy=self.cleaned_data['yyyy'] ##ERROR
if function_check(xxxx,yyyy)==False:
raise forms.ValidationError("Try again!")
return xxxx
In my template I have:
<form method="post" action="">
{% csrf_token %}
{{form.xxxx}}
<input id="id_yyyy" name="yyyy" type="hidden" value='{{ code_generated_value }}' maxlength="30">
<input type="submit"/>
</form>
The only error I get is : 'yyyy' at the yyyy=self.cleaned_data['yyyy'] line.
I found this question: Hidden field in Django form not in cleaned_data
But it was not very helping.
EDIT 1: Generated HTML code
<p><input id="id_xxxx" maxlength="30" name="xxxx" type="text" /></p>
<input id="id_yyyy" maxlength="30" name="yyyy" type="hidden" value='97a8eee9477b73dda401b15369f8db00a0d6ab79.png'>
<input type="submit"/>
Always check generated HTML and POST data for request. You will see any fields missing & stuff. Also, use .get(field_name) method.
Check here for more. How to properly access cleaned_data from super, etc.