我在使用django的formset时出现问题,当我只有一个formset时,来自POST的数据被存储但是在我添加第二个formset后,我只得到每个formset的最后一个输入。 以下是表格:
class OperationsForm( forms.Form ):
operation = forms.CharField(
required = True,
max_length = 20,
widget = forms.TextInput( attrs = {
'placeholder':'Operation Name'
} ),
)
class DataTypesForm( forms.Form ):
field = forms.CharField(
required = True,
max_length = 20,
widget = forms.TextInput( attrs = {
'placeholder':'Field Name'
} ),
)
type = forms.CharField(
required = True,
max_length = 20,
widget = forms.TextInput( attrs = {
'placeholder':'Field Type'
} ),
)
这是views.py:
def index( request ):
OperationsFormSet = formset_factory( OperationsForm )
DataTypesFormSet = formset_factory( DataTypesForm )
if request.method == 'POST':
operations_formset = OperationsFormSet( request.POST, prefix='operations' )
data_formset = DataTypesFormSet( request.POST, prefix='datas' )
if operations_formset.is_valid() and data_formset.is_valid():
operations_list = []
for operation_form in operations_formset:
operation = operation_form.cleaned_data.get( 'operation'
if operation:
print( operation )
operations_list.append( operation )
operations = ' '.join(operations_list)
operations = "\"" + operations + "\""
data_list = []
for data in data_formset:
dataName = data.cleaned_data.get( 'field' )
dataType = data.cleaned_data.get( 'type' )
if dataType and dataName:
dataToAdd = dataName + '-' + dataType
data_list.append( dataToAdd )
datas = ' '.join( data_list )
datas = "\"" + datas + "\""
print( "%s" % operations )
print( "%s" % datas )
#Do Something
return response
else:
operations_formset = OperationsFormSet( prefix='operations' )
data_formset = DataTypesFormSet( prefix='datas' )
context = { 'operations_formset': operations_formset, 'data_formset': data_formset }
return render( request, 'arquetipo/index.html', context )
这是index.html
<div class="maven-arguments">
<div class="row">
<div class="operations">
{% for f_form in operations_formset %}
<div class="operation-formset">
{{ f_form.as_table }}
</div>
{% endfor %}
{{ operations_formset.management_form }}
</div>
<div class="data">
{% for d_form in data_formset %}
<div class="data-formset">
{{ d_form.as_table }}
</div>
{% endfor %}
{{ data_formset.management_form }}
</div>
</div>
</div>
</br>
<button types='submit' value='generate'>Generar</button>
</form>
有人可以帮助我吗?
谢谢。
更新:
我忘了提到我在运行时使用JS来添加或删除额外的字段,这是代码:
<script>
$('.operation-formset').formset({
addText: 'Add operation',
deleteText: 'Delete'
});
$('.data-formset').formset({
addText: 'Add a field',
deleteText: 'Delete'
});
</script>