我正在尝试使用Django实现动态表单集。它正常工作,除了单击添加按钮时会添加两行具有相同ID的输入字段。应该只添加一行。
models.py
class StaffEmailCC(BaseModel):
staff_email = models.ForeignKey("projects.StaffEmail",blank=True,null=True)
cc_addresses=models.TextField(blank=True,null=True)
class Meta:
db_table = 'staffmailcc'
verbose_name = _('staffmailcc')
verbose_name_plural = _('staffmailcc')
ordering = ('-date_added',)
def __unicode__(self):
return self.cc_addresses
forms.py
class StaffEmailCCForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(StaffEmailCCForm, self).__init__(*args, **kwargs)
class Meta:
model = StaffEmailCC
fields = ['cc_addresses']
widgets = {
'cc_addresses': autocomplete_light.ChoiceWidget('StaffAutocomplete'),
}
views.py
def create_staff_mail(request):
StaffEmailCCFormset = formset_factory(StaffEmailCCForm)
staff_email_cc_formset = StaffEmailCCFormset(prefix='staff_email_cc_formset')
form = StaffEmailForm()
context = {
"form": form,
"staff_email_cc_formset":staff_email_cc_formset,
"title": "Create Staff Mail",
"sender_email":sender_email,
}
return render(request, 'projects/create_staff_mail.html', context)
HTML
<div class="content formElements add_item_container staff_email_cc_formset">
<table>
<tr>
<th>CC</th>
</tr>
{% for i in staff_email_cc_formset.forms %}
<tr class="form_set_row">
<td>
<span class="left cc_addresses">
{{i.cc_addresses}}
</span>
</td>
</tr>
{% endfor %}
</table>
{{ staff_email_cc_formset.management_form }}
</div>
js
$('.staff_email_cc_formset table tr.form_set_row').formset({
prefix: '{{ staff_email_cc_formset.prefix }}',
formCssClass: 'dynamic-formset1'
});
每次我单击“添加”按钮时,都会添加两行,其中只有一行可以自动完成。知道我在做什么错吗?
答案 0 :(得分:0)
Django表单集的默认设置为extra=1
。
[...]显示的空表格数量由extra参数控制。默认情况下,formset_factory()定义一种额外的形式[...]
Documentation:在页面中搜索extra=
,以快速找到所需的内容。
StaffEmailCCFormset = formset_factory(StaffEmailCCForm, extra=0)
答案 1 :(得分:0)
您可以将字段分配给表单集,
如果您这样编写表单集,则需要额外的字段默认值1:
StaffEmailCCFormset = formset_factory(StaffEmailCCForm)
您覆盖多余的字段 StaffEmailCCFormset = formset_factory(StaffEmailCCForm,extra = 1)
您可以看到formset.py的源代码 https://github.com/django/django/blob/master/django/forms/formsets.py
答案 2 :(得分:0)
这似乎很奇怪。但是将js函数放入$(document).ready(function(){});解决了我的问题
$(document).ready(function () {
$('.staff_email_cc_formset table tr.form_set_row').formset({
prefix: '{{ staff_email_cc_formset.prefix }}',
formCssClass: 'dynamic-formset1'
});
});