保存时排除内联formset中的id字段

时间:2016-10-22 03:44:04

标签: python django inline-formset

我有两个型号,通过外键连接。一个是内联formset。由于某种原因,formset id被标识为数据库中的主键,并且每次提交表单时,基本上都会覆盖属于formset的表。保存时,如何忽略formset ID

models.py

class Student(models.Model):
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

class Courses(models.Model):
    student = models.ForeignKey(Student)
    course_name = models.CharField(max_length=40)
    start_time = models.TimeField()

forms.py

class CoursesForm(forms.ModelForm):

    class Meta:
        model = Courses
        exclude = ("student",)


class StudentForm(forms.ModelForm):

    class Meta:
        model = Student
       fields = "__all__"

views.py ...

def post(self, request, *args, **kwargs):
    sform = StudentForm(request.POST, instance=Student())

    CourseSchedule = inlineformset_factory(Student, Courses, form=CoursesForm, can_delete=False, extra=0, min_num=1)

    cforms = CourseSchedule(data=request.POST)

    if sform.is_valid() and cforms.is_valid():

        sform_obj = sform.save()
        for cform in cforms.forms:
            cform_obj = cform.save(commit=False)
            cform_obj.student = sform_obj
            cform_obj.save()

    ....

1 个答案:

答案 0 :(得分:1)

我弄清楚了..我的表格数据在提交后仍然存在。我不得不在basemodelformset中声明一个空的queryset。