我有一个部门表单,其中包含用于部门IP列表的内联表单集。 我试图显示现有部门及其IP,并在需要时对其进行编辑,但是当我提交表单时,form的change_data可以正常工作,但是formset.has_changed总是返回true。
我可以使用此表单和表单集在另一个模板中添加部门,并且一切正常。 但是在这里我要编辑表单(添加/删除或编辑ips)。
models.py
class Department(models.Model):
name = models.CharField(unique=True, max_length=100)
username = models.CharField(max_length=100)
password = models.CharField(max_length=200)
class Meta:
managed = False
db_table = 'department'
class DepartmentIps(models.Model):
department = models.ForeignKey(Department, models.DO_NOTHING)
department_ip_from = models.CharField(unique=True, max_length=15)
department_ip_to = models.CharField(unique=True, max_length=15)
class Meta:
managed = False
db_table = 'department_ips'
forms.py
class DepartmentForm(ModelForm):
class Meta:
model = Department
DepartmentIPFormset = inlineformset_factory(Department, DepartmentIps, exclude=('department',),
widgets={'department_ip_from': forms.TextInput(
attrs={'size': '6', 'class': 'form-control'),
'department_ip_to': forms.TextInput(
attrs={'size': '6', 'class': 'form-control'), },
extra=0, can_delete=True, validate_min=True, min_num=1)
views.py
def setting_department(request, department=1):
currnet_d = Department.objects.get(id=department)
if request.method == "POST":
if 'add-department' in request.POST:
department_form = DepartmentForm(request.POST)
department_formset = DepartmentIPFormset(request.POST or None, instance=department_form.instance)
if department_form.is_valid() and department_formset.is_valid():
new_department = department_form.save()
department_formset.save()
if 'edit-department' in request.POST:
department_form = DepartmentForm(request.POST, prefix='edit', instance=currnet_d)
department_formset = DepartmentIPFormset(request.POST or None, prefix='editips')
print(department_formset.has_changed())
for formss in department_formset:
print(formss.changed_data)
print(department_form.has_changed())
department_form = DepartmentForm()
department_formset = DepartmentIPFormset()
edit_department_form = DepartmentForm(initial=initial_department, prefix='edit')
edit_department_formset = DepartmentIPFormset(instance=currnet_d, prefix='editips')
return render(request, 'config.html', locals())
在department_formsets.errors中,我为每个未更改的字段得到一个重复的字段。
如何检测数据是否已更改? 有什么办法可以访问表单集的changed_data?
提前谢谢。