我已经弄清楚了如何向表单域添加类。我有以下内容:
# models.py
class Contact(AddressMixin, PhoneMixin):
contact_id = models.AutoField(primary_key=True)
name = models.CharField(_('name'), max_length=50, blank=False)
company = models.CharField(_('company'), max_length=50, blank=True)
photo = models.CharField(_('photo'), max_length=255, blank=True)
notes = models.TextField(_('notes'), blank=True)
created_on = models.DateField(auto_now_add=True)
# forms.py
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = ['name', 'company', 'photo', 'notes']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
'company': forms.TextInput(attrs={'class': 'form-control'}),
'photo': forms.TextInput(attrs={'class': 'form-control'}),
'notes': forms.Textarea(attrs={'class': 'form-control'}),
}
神奇之处在于class Meta
,特别是widgets
字段。在这里,您可以定义要在哪个字段上进行的课程。但是,对于每个联系人,我希望能够添加1个或多个电话号码,因此我需要以下内容:
# models.py
class Phone(models.Model):
entity = models.ForeignKey('PhoneMixin', on_delete=models.CASCADE)
number = models.CharField(_('number'), max_length=50, blank=True)
class PhoneMixin(models.Model):
phone_id = models.AutoField(primary_key=True)
pass
# forms.py
class PhoneForm(ModelForm):
class Meta:
model = Phone
exclude = ['entity']
widgets = {
'number': forms.TextInput(attrs={'class': 'form-control'}),
}
然后我有一个表单集,我相信这是问题的根源:
PhoneFormSet = inlineformset_factory(
Contact,
Phone,
form=PhoneForm,
exclude=('entity',),
extra=1
)
我可能会误会,但我相信是表单集添加了删除字段。此删除字段最终在我的表单中成为复选框。当我检查该字段的html时,它的名称为DELETE
,所以我认为这就像将类添加到DELETE
形式的Phone
字段一样简单:
# forms.py
class PhoneForm(ModelForm):
class Meta:
model = Phone
exclude = ['entity']
widgets = {
'number': forms.TextInput(attrs={'class': 'form-control'}),
'DELETE': forms.CheckboxInput(attrs={'class': 'custom-control-input'}),
}
但是,这似乎没有做到。我什至尝试使用所有小写字母delete
,但还是没有运气。我怀疑原因是Django在评估表单之后在之后添加了DELETE
字段,但这只是一个猜测。所以我的问题是:
如何将类添加到Django动态添加到DELETE
表单的Phone
字段中?
答案 0 :(得分:0)
您可以在脚本中添加要删除的类复选框。请参考这个。
<table class="table">
{{ phone_form.management_form }}
{% for form in phone_form.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle 'row1' 'row2' %} phone_form_formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<script type="text/javascript" src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.phone_form_formset_row').formset({
addText: '<button type="button" class="btn btn-info">Add Contact</button>',
deleteText: '<button type="button" class="btn btn-danger">remove</button>',
prefix: 'phone_set'
});
</script>