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 ....
Related
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">
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!
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
Here is how my models are setup:
class ModelA(models.Model):
user = models.ForeignKey(User)
modelB = models.ForeignKey('ModelB', related_name='modelB')
# more fields here
class ModelB(models.Model):
user = models.ForeignKey(User)
# more fields here
The user field in both classes are just so that both of these can be queried by the same user later on.
I have a ModelForm of ModelB and I would like to have the users be able to fill out a ModelB ModelForm with a dynamic number of ModelA instances. I would like ModelB's form to start out with 1 instance of ModelA to fill out and then the user should be able to add more ModelA's to ModelB's form.
I'm stuck on this as a personal project and would really like to move forward. Thanks for any help!
Edit 1: I know that I will most likely need to do some work by overloading ModelForms def __init__, but that is about as far as I have gotten. Also I am using ClassBasedGeneric Views (CreateView to get the add working and an EditView later on), but I am willing to move away from that if needed.
You require django inline formset
In view:
f_set = inlineformset_factory(ModelB, ModelA, extra=1)
In template lets suppose you are rendering form_set in a div whose id is one_to_many:
<form>
<div id="one_to_many">
{{f_set.as_table}}
</div>
</form>
#This will render some thing like this
<form>
<div id="one_to_many">
<table>
<tr>
<th>
<label for="id_form-0-field_name">Field Name:</label>
</th>
<td>
<input id="id_form-0-field_name" type="text" name="form-0-field_name" value="" maxlength="100" />
<input type="hidden" name="form-0-id" value="1" id="id_form-0-id" />
</td>
</tr>
</table>
<input type="button" value="Add More Field" id="add_more">
</div>
</form>
Now the jquery part to add field dynamically:
$(document).ready(function(){
$('#add_more').click(function(){
var tbl = $('#one_to_many').children('table');
var last_id = parseInt(tbl.find('input[type=hidden]').last().val());
var next_id = last_id + 1;
htm = '<tr><th><label for="id_form-'+last_id+'-field_name">Field Name:</label></th><td><input id="id_form-'+last_id+'-field_name" type="text" name="form-'+last_id+'-field_name" value="" maxlength="100" /><input type="hidden" name="form-'+last_id+'-id" value="'+next_id+'" id="id_form-'+last_id+'-id" /></td></tr>'
tbl.find('tr').last().after(htm);
});
});
You can test this on jsfiddle. Note this will only work if you render your form as_table
This is the Html form:
<form action='use.py'>
<div><input type='text' name='etc'></div>
<p><input type='submit' value='etc!'></p>
</form>
And this is the python for it
colour = form["colour"].value
The top html form is a text box that users can type something in.
If I were to have a drop down box / radio button form like this:
<form action='etc.py'>
<p>List Type:</p>
<div><input type='radio' name='status' value='bulleted' checked>
Bulleted
</div>
<div><input type='radio' name='status' value='numbered'>
Numbered
</div>
<p>Text style:</p>
<div><input type='checkbox' name='bold'>
<b>Bold</b>
</div>
<div><input type='checkbox' name='italic'>
<i>Italic</i>
</div>
<p>Movies to display:</p>
<div>
<select name='type'>
<option>Only numbers</option>
<option>Only names</option>
</select>
</div>
<p><input type='submit' value='Display'></p>
</form>
How would I write my python? Like this?
only_numbers = form["Only numbers"].value
You can write a Python CGI script, but most Python frameworks are built upon WSGI and have a concept of request/response objects. For example, in Django the value would be available at request.POST['fieldname'].
Using the python CGI module, it is like:
form = cgi.FieldStorage()
# for multiple elements with same name or elements with multiple values
a_list = form.getlist("multiple_select_input")
# For single value elements
if "single_value_input" in form:
x = form["single_value_input"].value
else:
x = "default value"
# or
x = form.getvalue("single_value_input", "default value")