[Answer]-Django โ€“ How to fill modelform field from database when field not in model?

1๐Ÿ‘

โœ…

You need the data instead of initial

You can try this:

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()
๐Ÿ‘คkarthikr

Leave a comment