我正在尝试将 Django 生成的表单与 AJAX 调用一起用于数据填充。我只有一个普通的 ModelForm 工作,但是当我向它添加一个 inlineformset 时,我不知道应该在一些隐藏的 id 字段中填充什么值。每个提交都在创建一个新实例。对于有地址的学校,我的保存视图中有这个:
... get school logic here ...
if school_form.is_valid():
school = school_form.save(commit=False)
address_formset = AddressFormSet(request.POST, instance=school)
if address_formset.is_valid():
school_form.save()
address_formset.save()
... redirection logic here ...
这是填充我的表单的 JS。#id_address_set-0-school
并且#id_address_set-0-id
是 2 个 Django 生成的字段。
$('a[name^="editSchool"]').click( function(e) {
e.preventDefault();
$.ajax({
url: '/schooljson/' + this.getAttribute('schoolid') + '/'
}).done( function(data) {
$('#id_school_code').val(data.school_code);
$('#id_full_name').val(data.school_name);
$('#id_student_count').val(data.school_students);
$('#id_school_pk').val(data.school_pk);
$('#id_address_set-0-address_line_1').val(data.address_line_1);
$('#id_address_set-0-address_city').val(data.address_city);
$('#id_address_set-0-address_state').val(data.address_state);
$('#id_address_set-0-address_zip').val(data.address_zip);
$('#id_address_set-0-school').attr('value', data.school_pk);
$('#id_address_set-0-id').attr('value', data.address_pk);
$('#addSchoolModal').modal('show');
});
有什么想法我应该放在那里吗?