I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:
<input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" name="Project" value="2">Project 2</input>
<input type="checkbox" name="Project" value="3">Project 3</input>
<input type="checkbox" name="Project" value="4">Project 4</input>
<input type="checkbox" name="Project" value="5">Project 5</input>
In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me):
Project = formencode.foreach.ForEach(formencode.validators.Int())
I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails.
Anyone have any ideas?
maybe using formencode.validators.Set:
>>> Set.to_python(None)
[]
>>> Set.to_python('this')
['this']
>>> Set.to_python(('this', 'that'))
['this', 'that']
>>> s = Set(use_set=True)
>>> s.to_python(None)
set([])
>>> s.to_python('this')
set(['this'])
>>> s.to_python(('this',))
set(['this'])
redrockettt,
Have you looked at the docstring to variabledecode? It suggests you use something like:
<input type="checkbox" name="Project-1" value="1">Project 1</input>
<input type="checkbox" name="Project-2" value="2">Project 2</input>
<input type="checkbox" name="Project-3" value="3">Project 3</input>
Check out the text in variabledecode.py, or pasted here.
Related
I have the following form in a Django HTML template.
I found two different syntaxes that both work to pass string data from my form to the linked view function.
Please see the first radio input and then compare it the the second radio input to see the different syntax (on has brackets, one doesn't).
<form action="{% url 'shipment:createAccount' 1 %}" method="post">
{% csrf_token %}
<input type="radio" name="question_1" value="Option1">Option 1<br>
<input type="radio" name="question_1" value="{{ 'Option2' }}">Option 2<br>
<input type="submit" value="Confirm" />
</form>
I've found that my code works both ways. I was wondering if there is a functional difference between them, and if so, which one is preferable.
Actually, the second way is kind of overkill:
<input type="radio" name="question_1" value="{{ 'Option2' }}">Option 2<br>
You're telling the template engine to parse 'Option2' python statement. Since 'Option2' python statement yields a string, the template engine will substitute it with:
<input type="radio" name="question_1" value="Option2">Option 2<br>
Which is exactly the same as your first way. You're creating a little overhead by doing it the second way.
Brackets are used inside templates to perform some kind of computation inside the template domain. Like accessing a view's variable or object method.
To answer your question, you don't need the brackets syntax to include literals in the template. You need them to output variable values in it.
Hope this helps!
I have the following HTML code:
<form method="post">
<h5>Sports you play:</h5>
<input type="checkbox" name="sports_played" value="basketball"> basketball<br>
<input type="checkbox" name="sports_played" value="football"> football<br>
<input type="checkbox" name="sports_played" value="baseball"> baseball<br>
<input type="checkbox" name="sports_played" value="soccer"> tennis<br>
<input type="checkbox" name="sports_played" value="mma"> MMA<br>
<input type="checkbox" name="sports_played" value="hockey"> hockey<br>
<br>
<input class="btn" type="submit">
</form>
And then ideally I would like to have the following python serverside code:
class MyHandler(ParentHandler):
def post(self):
sports_played = self.request.get('sports_played')
#sports_played is a list or array of all the selected checkboxes that I can iterate through
I tried doing this by making the HTML sports_played name and array, sports_played[], but that didn't do anything and right now it just always returns the first selected item.
Is this possible? Really I just don't want to have to do a self.request.get('HTML_item') for each and every checkbox incase I need to alter the HTML I don't want to have to change the python.
Thanks!
The answer is shown in the webapp2 docs for the request object:
self.request.get('sports_played', allow_multiple=True)
Alternatively you can use
self.request.POST.getall('sports_played')
The name of the inputs should have [] at the end so that they are set to the server as an array. Right now, your multiple checkboxes are being sent to the server as many variables with the same name, so only one is recognized. It should look like this:
<form method="post">
<h5>Sports you play:</h5>
<input type="checkbox" name="sports_played[]" value="basketball"> basketball<br>
<input type="checkbox" name="sports_played[]" value="football"> football<br>
<input type="checkbox" name="sports_played[]" value="baseball"> baseball<br>
<input type="checkbox" name="sports_played[]" value="soccer"> tennis<br>
<input type="checkbox" name="sports_played[]" value="mma"> MMA<br>
<input type="checkbox" name="sports_played[]" value="hockey"> hockey<br>
<br>
<input class="btn" type="submit">
</form>
Now, if you select more than one, the values will be sent as an array.
Although this answer is not related to this question, but it may help all the django developers who is walking here and there.
In Django request.POST is a QueryDict object. So you can get all the values as list by following way
request.POST.getlist('sports_played')
N.B: This only works in Django
I am passing multiple form fields which are optional, but which need to be associated with a user. Python's cgi.FormDict and cgi.FieldStorage both eliminate blank entries, so items get shifted "up" and associated with the wrong user.
This problem most often shows up with checkboxes (which I have), but I also have text fields.
Simplified form code:
<input type="text" name="user" />
<input type="text" name="email" />
<input type="text" name="phone" />
<input type="checkbox" value="MailingList1" />
<input type="checkbox" value="MailingList2" />
<p>
<input type="text" name="user" />
<input type="text" name="email" />
<input type="text" name="phone" />
<input type="checkbox" value="MailingList1" />
<input type="checkbox" value="MailingList2" />
etc...
Users are required enter EITHER email or phone (or both) but can leave the other blank.
Now say I have input like this:
john_doe john_doe#example.com (123) 555-1234 Y Y
jane_roe jane_roe#example.com Y
george_jetson george_jetson#future.com (321) 555-4321 Y
The FormDict looks something like this:
{
'username':['john_doe','jane_roe','george_jetson'],
'email':['john_doe#example.com','jane_roe#example.com','george_jetson#future.com'],
'phone':['(123) 555-1234','(321) 555-4321'],
'MailingList1':['Y','Y'],
'MailingList2':['Y','Y']
}
I'm looping through like this:
for i in range(len(myFormDict['username'])):
username = myFormDict['username'][i]
email = myFormDict['email'][i]
phone = myFormDict['phone'][i]
MailingList1 = myFormDict['MailingList1'][i]
MailingList2 = myFormDict['MailingList2'][i]
...Inserts into the database
Before you ask, Yes, I do have error traps to prevent it from running off the end of the lists and all. The code works fine, but my database ends up looking like this:
john_doe john_doe#example.com (123) 555-1234 Y Y
jane_roe jane_roe#example.com (321) 555-4321 Y Y
george_jetson george_jetson#future.com
Jane and George are going to be pretty mad at me.
So... how do I keep the blanks so the right phone numbers and list memberships line up with the right users?
All the answers I've found searching the web involve a framework like GAE, Django, Tornado, Bottle, etc.
Bottle is lightest weight, but I tried it and it requires Python 2.5 and I'm stuck on 2.4.
If these frameworks can do it, it has to be possible. So how can I manage my data properly with just the standard library?
Thanks.
Look at the doc below (namely, keep_blank_values parameter):
>>> print cgi.FieldStorage.__init__.__doc__
Constructor. Read multipart/* until last part.
Arguments, all optional:
fp : file pointer; default: sys.stdin
(not used when the request method is GET)
headers : header dictionary-like object; default:
taken from environ as per CGI spec
outerboundary : terminating multipart boundary
(for internal use only)
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in
percent-encoded forms should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
I'm not sure if you can tweak cgi.FromDict to do what you want,
but maybe a solution would be to make every input set uniqe like so:
<input type="text" name="user" />
<input type="text" name="email" />
<input type="text" name="phone" />
<input type="checkbox" value="MailingList1_1" />
<input type="checkbox" value="MailingList2_1" />
<p>
<input type="text" name="user" />
<input type="text" name="email" />
<input type="text" name="phone" />
<input type="checkbox" value="MailingList1_2" />
<input type="checkbox" value="MailingList2_2" />
Note thate MailingList1 and Mailinglist2 now hafe a suffix for the "entry block".
You will have to add this at generation time of you Form and then adapt your processing accordingly by reading the checkboxes like so:
lv_key = 'MailingList1_' + str(i)
MailingList1 = myFormDict[lv_key]
...
Regards,
Martin
Even if you're using wsgi based frameworks like django or bottle, you're using same <input> names for each field - cgi formdict does not eliminate empty fields, there are no empty fields in the first place. you should give different name attribute for each user.
I'm two days in to Python and GAE, thanks in advance for the help.
I have an input array in HTML like this:
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
I want to parse the input in Python, and I'm trying this, which isn't working:
items = self.request.get('p_item')
for n in range(1,len(items)):
self.response.out.write('Item '+n+': '+items[n])
What is the correct way to do this?
Change your html to this
<input type="text" name="p_item">
<input type="text" name="p_item">
<input type="text" name="p_item">
and use the self.request.get_all() method http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_get_all
p.s. For reference, there is no concept of arrays for GET/POST data, your form gets transformed a key=value string separated by '&' e.g.
p_item=1&p_item=3&p_item=15
etc, it's up to the web framework to interpret whether a parameter is an array.
Edit: oops, just read the comments that you figured this out already, oh well :P
I would recommend doing some debugging if this sort of issue comes up. Make things simple and write out your variable values and ensure you get what you expect at each step. Do something like the following:
<form method="get">
<input type="text" name="single_key" />
<input type="text" name="array_key[some_key]" />
<input type="submit" />
</form>
And see what happens when running the following Python on the backend:
single_value = self.request.get('single_key')
self.response.out.write(str(single_value))
array_value = self.request.get('array_key')
self.response.out.write(str(array_value))
Based on the output you should have a better idea of what to get the desired results or how to add more detail to your question if you still don't understand a certain behavior.
Is there any way for Pyramid to process HTML form input which looks like this:
<input type="text" name="someinput[]" value="" />
or even more usefully:
<input type="text" name="someinput[0][subelement1]" value="" />
<input type="text" name="someinput[0][subelement2]" value="" />
<input type="text" name="someinput[1][subelement1]" value="" />
<input type="text" name="someinput[1][subelement2]" value="" />
...and access that data easily (e.g. via a dict)?
Any help would be much appreciated!
EDIT: to make it clearer, what I need is the ability to have a form where a user can add as many 'instances' of a group of input elements, e.g. adding between 1 and n users, each containing a firstname, lastname, username (or something like that).
One solution would be to use peppercorn. Although it does not support the syntax you're looking for, it will let you send structured data to your Pyramid application through the use of forms. A more casual description exists too.