I'm having problems with processing custom form data...
<input type="text" name="client[]" value="client1" />
<input type="text" name="address[]" value="address1" />
<input type="text" name="post[]" value="post1" />
...
<input type="text" name="client[]" value="clientn" />
<input type="text" name="address[]" value="addressn" />
<input type="text" name="post[]" value="postn" />
... (this repeats a couple of times...)
If I do
request.POST.getlist('client[]')
request.POST.getlist('address[]')
request.POST.getlist('post[]')
I get
{u'client:[client1,client2,clientn,...]}
{u'address:[address1,address2,addressn,...]}
{u'post:[post1,post2,postn,...]}
But I need something like this
{
{0:{client1,address1,post1}}
{1:{client2,address2,post2}}
{2:{client3,address3,post3}}
...
}
So that I can save this data to the model. This is probably pretty basic but I'm having problems with it.
Thank you!
Firstly, please drop the [] in the field names. That's a PHP-ism that has no place in Django.
Secondly, if you want related items grouped together, you'll need to change your form. You need to give each field a separate name:
<input type="text" name="client_1" value="client1" />
<input type="text" name="address_1" value="address1" />
<input type="text" name="post_1" value="post1" />
...
<input type="text" name="client_n" value="clientn" />
<input type="text" name="address_n" value="addressn" />
<input type="text" name="post_n" value="postn" />
Now request.POST will contain a separate entry for each field, and you can iterate through:
for i in range(1, n+1):
client = request.POST['client_%s' % i]
address = request.POST['address_%s' % i]
post = request.POST['post_%s' % i]
... do something with these values ...
Now at this point, you probably want to look at model formsets, which can generate exactly this set of forms and create the relevant objects from the POST.
Related
I have the following form in my forms.py :
class PaymentMethodForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PaymentMethodForm, self).__init__(*args, **kwargs)
payment_choices = ['online payment', 'payment at delivery']
self.payment_method_choice = forms.ChoiceField(choices=payment_choices, widget=forms.RadioSelect)
now this is the page in an online shop where you select your payment method. as you see, we have two methods, one is payment at delivery time which means there should not be any payments in the website, and the other one is online payment. In the case of the user choosing online payment, I should submit a form via post that looks something like this and after that redirect the user to the action url :
<form id="Form2" method="post" Action="https://somepaymentsite.com/gateway.aspx"
>
<input type="hidden" name="invoiceNumber" value="<%= invoiceNumber %>"
/>
<input type="hidden" name="invoiceDate" value="<%= invoiceDate %>" />
<input type="hidden" name="amount" value="<%= amount %>" />
<input type="hidden" name="terminalCode" value="<%= terminalCode %>" />
<input type="hidden" name="merchantCode" value="<%= merchantCode %>" />
<input type="hidden" name="redirectAddress" value="<%= redirectAddress
%>" />
<input type="hidden" name="timeStamp" value="<%= timeStamp %>" />
<input type="hidden" name="action" value="<%= action %>" />
<input type="hidden" name="sign" value="<%= sign %>" />
<input type="submit" name="submit" value=""continue />
</form>
now what I have in mind for doing this is that instead of putting this html stuff in my template (html file) I will get the radio button choice the user has chosen and if they chose online payment, I will submit a form like the above in my views.py . the problem is, I do not know how to go about this. I googled things but I didn't find anything good on how to post a form in a view in django. Can anybody help me? thanks.
If I understood correctly, "submit form from the view" is the same as do POST request to https://somepaymentsite.com/gateway.aspx with data {'invoiceNumber': 12345, 'invoiceDate': '10.10.2015', ...}. You can use requests library in this case.
# in view
# if online payment then
r = request.post('https://somepaymentsite.com/gateway.aspx', data=payload)
# processing r (error handling or something else)
where payload is dictionary {'invoiceNumber': 12345, 'invoiceDate': '10.10.2015', ...} that you construct somehow.
So, I've hacked this together from a few sources, so if I'm totally going about it the wrong way I welcome feed back. It also occurs to me that this is not possible, as it's probably a security check designed to prevent this behavior being used maliciously.
But anyway:
I have a form on our Django site where people can request to change the name of one of our items, which should automatically create a jira ticket. Here's the form:
<form target="_blank" action='http://issues.dowjones.net/secure/CreateIssueDetails!init.jspa' method='get' id='create_jira_ticket_form'>
<a id='close_name_change_form' class="close">×</a>
<label for="new_name">New name: </label>
<input id="new_name" type="text" name="new_name" value="{{item.name}}">
<input type="hidden" value="10517" name="pid">
<input type="hidden" value="3" name="issuetype">
<input type="hidden" value="5" name="priority">
<input type="hidden" value="Change name of {{item.name}} to " name="summary" id='summary'>
<input type="hidden" value="{{request.user}}" name="reporter">
<input type="hidden" value="user123" name="assignee">
<input type="hidden" value="" name="description" id="description">
<input id='name_change_submit' class="btn btn-primary btn-sm" type="submit" value="Create JIRA ticket">
</form>
Then I have a little JS to amend the fields with the new values:
$(document).ready(function(){
$('#create_jira_ticket_form').submit(function(){
var watchers = ' \[\~watcher1\] \[\watcher2\]';
var new_name = $('#new_name').val();
var summary = $('#summary').val();
$('#summary').val(summary + new_name);
$('#description').val(summary + new_name + watchers);
})
})
It comes very close to working, but the description field is escaped, leaving it looking like:
Change name of OLDNAME to NEWNAME %5B%7Ewatcher1t%5D %5B%7Ewatcher2%5D
Which is less than helpful. How can I keep it as is so I can add watchers?
This happens when your form encodes the fields and values in your form.
You can try this out by this simple snippet:
console.log($('form').serialize());
you should see something like
description=ejdd+%5B~watcher1%5D+%5Bwatcher2%5D
in order to prevent this you should change your method='get' to method='post'.
The encoding happens because it's apart of HTTP, read here why
You can also read the spec paragraph
17.13.3 Processing form data
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.
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.