0

如何在验证之前用数据库中的值填充模型表单中的非模型字段?

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__表格,我一直在接近,但不能完全实现。

4

1 回答 1

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()

或者

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()
于 2013-06-24T16:01:15.730 回答