在formsets中设置外键

时间:2014-02-20 08:16:17

标签: django

我收到此错误

  

reports_student.classroom_id可能不是NULL

这是我的看法。我在这做错了什么?我认为问题是由设置外键引起的。课堂属于用户......学生属于课堂......

def build_classroom(request):
    print "building classroom"
    # Empty formset forms should be required
    class RequiredFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(RequiredFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False
    StudentFormSet = formset_factory(StudentForm, max_num=100, formset=RequiredFormSet)
    if request.method == 'POST': # If the form has been submitted...

        classroom_form = ClassroomForm(request.POST)
        student_formset = StudentFormSet(request.POST, request.FILES)

        if classroom_form.is_valid() and student_formset.is_valid():
            classroom = classroom_form.save(commit=False)
            classroom.user = request.user
            for form in student_formset.forms:
                student = form.save(commit=False)
                student.classroom = classroom
                student.save()
            return HttpResponseRedirect('/') # Redirect to a 'success' page
    else:
        classroom_form = ClassroomForm()
        student_formset = StudentFormSet()

    # For CSRF protection
    # See http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ 
    c = {'classroom_form': classroom_form,
         'student_formset': student_formset,
        }
    c.update(csrf(request))

    return render_to_response('reports/build_classroom.html', c)

1 个答案:

答案 0 :(得分:1)

classroom = classroom_form.save(commit=False)

由于您在课堂表单中使用了commit=False,因此classroom可能没有可分配给student的ID值。

首先保存教室实例(省略commit=False)。

    if classroom_form.is_valid() and student_formset.is_valid():
        classroom = classroom_form.save(commit=False) # So you can add FK
        classroom.user = request.user # exclude("user",) in forms.py so it validates
        classroom.save() # put it in the database for student
        for form in student_formset.forms:
            student = form.save(commit=False)
            student.classroom = classroom # classroom is in the database
            student.save()
        return HttpResponseRedirect('/')