我有一个用例,用户可以更新现有的嵌入式表单集,也可以将其另存为新的表单集(可能已经编辑过,也可能没有编辑过)。保存新表单时,需要保留原始表单,以便您留有2个内联表单集。我遇到的困难是从现有表单集中保存新的表单集。我无法获得新的父模型来链接到子模型。
我怀疑这与表单集ID(例如:my_formset-0-id
)有关(据我了解),该表单集ID仅在编辑字体集时出现。因此,当我尝试保存新的表单集时,由于存在ID,因此期望进行更新。我当时以为一种解决方案是在编辑时删除表单集的id字段,但这似乎有点骇人听闻。也许有人会澄清表单集是否确实以这种方式运行。
views.py
def pivot_report_post_modal(request, report_type=None, report_id=None):
"""View for a POST that creates a new pivot report view or edits an existing one
"""
if report_type: # new
pivot_report = get_object_or_404(PivotReport, identifier=report_type)
report_view = PivotReportView(pivot_report=pivot_report, default=False, client=request.user.client)
elif report_id: # edit
report_view = get_object_or_404(PivotReportView, id=report_id, client=request.user.client)
pivot_report = report_view.pivot_report
report_type = pivot_report.identifier
else:
raise Http404
FormSet = inlineformset_factory(PivotReportView, AndReportFilter, form=AndReportFilterForm, extra=0, min_num=0)
if request.method == 'POST':
data = json.loads(request.body.decode("utf-8"))
formset_post = data['filters']
form = ReportSetupForm(data, instance=report_view)
formset = FormSet(formset_post, instance=report_view,
form_kwargs={'user': request.user, 'report_type': report_type})
if form.is_valid():
instance = form.save(user=request.user, pivot_report=pivot_report, commit=False)
if formset.is_valid():
if instance.temp_report:
PivotReportView.objects.filter(
client=request.user.client, pivot_report=pivot_report, temp_report=True
).delete()
report_view.label = 'Temp'
report_view.clear_all() # removes all foreign key relationships
instance.save()
create_report_view_items(instance, data)
formset = FormSet(formset_post, instance=instance,
form_kwargs={'user': request.user, 'report_type': report_type})
assert formset.is_valid()
formset.save()
context = {'success': True, 'id': report_view.id, 'label': report_view.label}
return JsonResponse(context)
return JsonResponse({'success': False})