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...
Related
I am trying to extract text from the following HTML code:
#app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
H_desiderata = float(request.form.get('H_desiderata')) #THIS CAUSES THE ERROR
return render_template('form1.html')
HTML below:
<body>
<h2>Brioche Recipe</h2>
<form>
<div class="grid-container">
<div class="grid-item">
<label class="text" for="H_desiderata">
H_desiderata:
</label><be>
<input type="number" id="H_desiderata" name="H_desiderata1"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
Before putting it into a grid it worked:
old working code:
<form>
<label for="H_desiderata">H_desiderata:</label><br>
<input type="number" id="H_desiderata" name="H_desiderata"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
How should I adapt request.form to return the value within the input box?
There is so much wrong with your code, but let's start with this:
request.form is empty when request.method == "GET. So. request.form['H_desiderata'] will give a key error.
Move that to the POST section of your view. Also, use request.form.get('H_desiderata', -9999999) in case it's not defined.
UPDATE:
OK, now try:
if request.method == 'POST':
print(request.form)
print(request.form.get('H_desiderata'))
print(float(request.form.get('H_desiderata')))
H_desiderata = float(request.form.get('H_desiderata'))
Then, you are going to want:
return render_template('form1.html', val_H_desiderata=H_desiderata)
UPDATE2:
Your <form> tag is malformed. Try:
<form action="/" method="post">
UPDATE3:
You change the name of the input, so change to: request.form.get('H_desiderata1')
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()
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.
Hi I got a simple form for a POST request and it works when I'm only having one input, but not two inputs together. Can someone show me some light on this?
index.html
<form name="input" action="{% url 'sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="recipient">
<br>
Message: <input type="text" name="content">
<br>
<input type="submit">
</form>
views.py
def sending(request):
recipient = request.POST.get('recipient','')
content = request.POST.get('content','') #not working when I am doing this...
someMethod(recipient, content)
return HttpResponseRedirect(reverse('results'))
Adding a "forms" portion to your setup will help you greatly... see the quickstart docs on forms here: https://docs.djangoproject.com/en/1.6/topics/forms/
In particular, check out "using a form in a view": https://docs.djangoproject.com/en/1.6/topics/forms/#using-a-form-in-a-view
Basically, you end up with a "forms.py" file which defines your form fields. Then, after it all processes, you get a simplier API into your form fields that looks like this:
form.cleaned_data['recipient']
form.cleaned_data['content']
etc.
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.