BUMP - django form request.POST.get('field-name', '') always empty - python

Trying to get some values from a form but the parameters are always empty. here is the path from my urls.py:
url((r'^partners-email$'), views.partners_email, name="Partners Email"),
This is a simple form I have in the template:
<form method="POST" action="/partners-email">
<input name="email" class="form-control" id="client-email">
<input type="submit" value="Submit" />
</form>
and here is my function in views.py:
def partners_email(request):
from_email = request.POST.get('email', '')
print('MY_TAG: ' + from_email)
output is always:
"MYTAG: "
any ideas?
Thank you very much in advance

Your input elements don't have a name attribute so the browser will never send data for them.

Try it.
<input type="text" name="email" class="form-control" id="client-email">

Related

Upload file in flask with other form elements fails with 400 error

Getting a 400, when trying to upload a file ad send other form elements to flask from html. Tried to use ajax, but that throws me an error as well.
Python:
#app.route('/prod_diff_result', methods=['POST', 'GET'])
def prod_diff_result():
try:
host = request.form['host-prod-iterator']
print(host)
if request.files['file']:
f = request.files['file']
f.save(secure_filename(f.filename))
HTML:
<div class="main-div">
<form action="/prod_diff_result" method="POST" enctype="multipart/form-data">
<div class="grid-container">
<div class="grid-item">
<span class="label label-default ">PROD</span><br>
<p>Iterator Host : <input type="text" class="form-control" id="host-prod-iterator" value="10.47.7.57"
required></p>
<input type="radio" name="data_fetch_type" value="file" onclick="showfile()">Upload File
<input type="file" name="file" />
<input type="radio" name="data_fetch_type" value="db"> Get from DB
<input type="submit" />
</div>
</form>
</div>
I want to be able send hostname and file back to flask error in one request and using one form.
It gives an error because you try to access a form field that it cannot find, and assumes that somehow the request was bad, because it didn't include a required form field. You are trying to access:
host = request.form['host-prod-iterator']
However you have simply not given it a name in your HTML. If you give it a name, it should work:
<p>Iterator Host :
<input type="text" class="form-control" name="host-prod-iterator" id="host-prod-iterator" value="10.47.7.57" required>
</p>

How to get a list of values with WTForms in Flask?

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!

Keep text from escaping / add watchers to Jira ticket

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

Key error: html 5 form submission using pyramid

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.

access to generic form field in template

I have a form with generic fields
forms.py
class OfferForm(forms.ModelForm):
class Meta:
model=Offer
some_views.py
def add_field(request):
form = OfferForm()
#some logic here
for x in list:
form.fields[x]=forms.ModelChoiceField(queryset=some_query)
return render_to_response(template,{'form':form,'list_of_add_field':list}
So , In my template i want to do something like this:
{%for x in list_of_add_field%}
Name add field is {{x}}
Choices:
{%for y in form.{{x}}.choices %}
<input type="checkbox" name="form.{{x}}.html_name">y </input>
{%endfor%}
{%endfor%}
How can do that ? Any idea ?
Thank you !
I see you are intended to do and here my reply. You should adapt your code to django and not django to your code. In this way, to solve your issue, the 'prefix' form resource is the right option:
You can put several Django forms inside one tag. To give each Form its own namespace, use the prefix keyword argument:
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print mother.as_ul()
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
>>> print father.as_ul()
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
In your case, you can make a new form for each X of your list. Put all new forms in a list named formset. Then, in your template, you should write form loop:
{{for form in formset}}
... Here your code for a form ....

Categories

Resources