I have a very simple pyramid/pylons web app with only one page (home) detailed on the home.pt template shown below:
<form action="/" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<fieldset>
<div>
<input type="radio" name="myradio" value="left" id="choice1"/>
<label for="choice1">Choice1</label>
<input type="radio" name="myradio" value="right" id="choice2"/>
<label for="choice2">Choice2</label></div>
<p>Form Controls</p>
<input type="submit" name='form.submitted' value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
</form>
This is the view config associated with it:
#view_config(route_name='home', renderer='templates/home.pt')
def home(request):
choices=random.sample(ranges.items(),2)
choice1=choices[0]
choice2=choices[1]
output=request.GET["myradio"]
return {'choice1':choice1,'choice2':choice2, 'output':output, "myradio":myradio}
This gives me a simple KeyError: 'myradio'.
edit: If I need any more detail, please don't hesitate to ask.
You should be able to just do request.POST.get('myradio'), and that would return you 'left' or 'right' depending on which is selected.
Ok, so here is what I did to fix it.
Instead of
output=request.GET["myradio"]
I now have
post_data=request.POST
output=post_data.get('myradio')
of course I also had to change the form to a get form (updated above in the question)
This gives an output of "left" if I select the left button and submit and an output of "right" if I select the right button and submit.
Related
Intro: I can receive the values from input fields in Flask by
var = request.form['description']
and the following HTML:
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="description">Beschreibung</label>
<textarea name="description" placeholder="Post description"
class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Question: Any idea how to handle a tag field, like e.g. Link , together with Flask Form? How to handle Flask Form and $.Ajax Post request simultaneously? Any hint would be highly appriciated. I did my research but found nothing online.
I found now an easy solution for me. DonĀ“t know if it is very clean but what I did was basically create a hidden field and pass the var from JS to the hidden field inside <form so that i can grab it with request in Flask. I also did this the other way around, passing the variable from Flask to JS. In this way I can use the CSS,JS in the link above outside of <form, i.e. I can press Enter
HTML:
<!-- from JS to Flask -->
<input type="hidden" name="hidden_tags" id="hidden_tags" value="" />
<!-- from Flask to JS -->
<input type="hidden" name="hidden_tags2" id="hidden_tags2" value="{{ post['tags'] }}"/>
in JS:
tags = document.getElementById("hidden_tags2").value.split('/');
document.getElementById("hidden_tags").value = tags
in Flask:
request.form['hidden_tags']
So, last few days I was trying to build a website where you input the post data then hit submit and then boom your post appears on the home page/post page.
So, I have created the form but the problem is that I don't know how to send HTML form data to SQLite database so it can be viewed by multiple users anytime.
<form class="posts" action="." method="post">
<h2>Title</h2>
<input type="text" name="title" placeholder="Title">
<h2>Description</h2>
<textarea input class="des" name="description"type="text" placeholder="Description"></textarea>
<h2>Image(Optional)</h2>
<input type="file" name="inpFile" id="inpFile" class="img-btn">
<div class="img-prev" id="imgPrev">
<img src="" alt="Image Preview" class="img-prev__img">
<span class="img-prev__def-text">Image Preview</span>
</div>
<input type="submit" value="Submit">
</form>
I think that you should take a look at some Python's web-frameworks like Flask or Django first, so that you can understand this subject a little clearer.
In the website I'm building with Flask I'm using WTForms to validate submitted forms. In one form, I'm submitting a list of values with a form like this (the hidden fields are generated client side using js):
<form action="" method="post" id="prop-form">
<input type="hidden" name="ids[]" value="54511ea9c1a36b4e910ce52a">
<input type="hidden" name="ids[]" value="54511ea9c1a36b4e910ce52d">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this form">
</form>
On the Flask side, I can easily get the contents of ids[] using he following code:
print request.form
print request.form.getlist('ids[]')
prints out:
ImmutableMultiDict([('ids[]', u'54511ea9c1a36b4e910ce52a'), ('ids[]', u'54511ea9c1a36b4e910ce52d'), ('title', u'Blablabla')])
[u'54511ea9c1a36b4e910ce52a', u'54511ea9c1a36b4e910ce52d']
But when I create a SelectMultipleField in my wtform as follows:
ids = SelectMultipleField('ids[]')
and then try to get those values, I get an empty list:
print form.ids.data # prints out []
Any idea how I could mimic the behaviour of request.form.getlist('ids[]') using WTForms? All tips are welcome!
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'm wondering why this is happening:
I'm sending file data with form in POST, but all the time it says:
Key 'file' not found in <QueryDict:
{
u'datum': [u'aaa'],
u'csrfmiddlewaretoken': [u'USAbRrgU92yj7KFpZHuxf9bWufgnwC4N'],
u'anzeige': [u' aaaa'],
u'titel': [u' aaa']
}
This is my html:
<form id="myform" action="/anzeige_save/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea style="width: 450px" id="titel" name="titel"> </textarea>
<textarea name="anzeige" id="anzeige"
style="height: 180px; width: 450px"> </textarea>
<input type="text" id="datum" name="datum" >
<input type="file" id="file" name="file" size="40" maxlength="100000">
<input type="button" value="speichern"
onclick="javascript:submitform()" />
</form>
<script>
function submitform(){
document.forms["myform"].submit();
}
</script>
and part my view is this:
anzeige=Anzeige(titel=request.POST['titel'],
anzeige=end_anzeige,
date=datetime.datetime.now(),
datum=request.POST['datum'],
file=request.FILES['file'])
anzeige.save()
I'm actually submitting correctly, the form should also submit the file in QueryDict like other queries. Can someone help me to figure out what I'm missing here?
Thanks
Use a ModelForm instead of a form, unless you have a good reason not to.
Your HTML will display a blank form if the form doesn't validate, without mentioning the errors nor previously entered values, see customizing a form template for correct usage.
It is normal that request.POST['file'] does not exist, it's in request.FILES['file'], but it must be saved before it can be used in a model. If you use a ModelForm, it is automatic. Else, see handling uploaded files with a model.