Hallo,
ich werkel gerade an einer privaten Rezepteverwaltung und - auch motiviert durch den Thread hier - bin ich das Thema "dynamische Formularerweiterung" auch mal angegangen.
Folgender Prototyp funktioniert:
Server:
Code: Alles auswählen
from bottle import route, run, template, debug, static_file, request
from my_forms2 import InputForm2
@route('/test')
def index():
form = InputForm2()
return template('dyn_form_in_wt2.html', form=form)
@route('/test', method='POST')
def post_data():
form_data = request.forms
form = InputForm2(form_data)
for k, v in form_data.items():
print(k, v)
if not form.validate():
print(form.errors)
else:
print('Form is valid')
return 'Done'
@route('/static/<filename>')
def server_static(filename):
return static_file(filename, root='/home/noisefloor/code/bottle/dyn_form/static')
debug=True
run(host='localhost', port=8080, reloader=True)
Formular:
Code: Alles auswählen
from wtforms.form import Form
from wtforms.fields import StringField, SelectField, DecimalField, FormField, FieldList
from wtforms.validators import NumberRange, InputRequired
UNITS = [('kg', 'kg'),
('g', 'g'),
('TL', 'TL'),
('EL', 'EL'),
('St', 'St')]
class InputForm(Form):
description = StringField('description',
[InputRequired()])
unit = SelectField('unit', choices=UNITS)
quantity = DecimalField('quantity',
[InputRequired(), NumberRange(min=0)],
places=3)
class InputForm2(Form):
ingredients = FieldList(FormField(InputForm), min_entries=1)
Template:
Code: Alles auswählen
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Forms</title>
<script src="static/jquery-2.2.0.min.js"></script>
</head>
<body>
<form action="/test" method="POST">
<button class="add_field_button">Mehr Felder...</button>
<div class="input_fields_wrap">
<!-- here goes the form fields -->
</div>
<input type="submit">
</form>
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var html_string = '{{ !form.ingredients }}<a href="#" class="remove_field">Remove</a>';
var x = -1; //initlal text box count
$(wrapper).append(make_string());
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(make_string());
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
});
function make_string() {
var my_string = html_string;
var output = ''
output = my_string.replace(0, x+1, "g");
return output;
};
});
</script>
</body>
</html>
Das JS ist ein angepasstes Beispiel aus dem Web - das ist nicht alles auf meinem Mist gewachsen.
Vielleicht nützt es ja was für das ähnliche, hier beschriebene Problem
Gruß, noisefloor