如何在验证前使用数据库中的值填充模型中的非模型字段?
if request.POST:
formset = StudentScheduleFormSet(request.POST,)
for form in formset:
if not form.initial.get('course_term'):
form.initial['course_term'] = CourseTerm.objects.get(course=form.data['course'], term=form.data['term'])
if form.is_valid():
form.save()
if formset.is_valid():
formset.save()
我已经尝试了这个以及其他大约20种变体,包括在表单上修改__init__
并且我一直在接近但不能完全实现它。
答案 0 :(得分:1)
您需要data
而不是initial
你可以试试这个:
if request.POST:
formset = StudentScheduleFormSet(request.POST,)
for form in formset:
if not form.data['course_term']:
form_obj.course_term = CourseTerm.objects.get(course=form.cleaned_data['course'], term=form.cleaned_data['term'])
if form.is_valid():
form.save()
if formset.is_valid():
formset.save()
OR
if request.POST:
formset = StudentScheduleFormSet(request.POST,)
for form in formset:
if form.is_valid():
if not form.cleaned_data.get('course_term'):
form_obj = form.save(commit=False)
form_obj.course_term = CourseTerm.objects.get(course=form.cleaned_data['course'], term=form.cleaned_data['term'])
form_obj.save()
else:
form.save()
if formset.is_valid():
formset.save()