尝试保存多对多字段数据时的完整性错误

时间:2018-02-27 10:45:56

标签: python django

我有一个课程模型和一个StudentData模型。为了让学生注册课程,我在课程模型中添加了多对多字段。我可以使用复选框列出学生,但问题是,当我按下“注册”按钮时,将这些学生添加到课程中时,我收到以下错误:http://dpaste.com/3E1XR4P

#views.py

if request.method == "POST":
        form = CourseForm(request.POST)
        if form.is_valid():
            form.save()
            redirect('classroom')
    else:
        form = CourseForm()

#forms.py

     class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ('student', )
        widgets = {
            'student': forms.CheckboxSelectMultiple
        }

#models.py


class StudyProgramme(models.Model):
    department = models.ForeignKey('Department', on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    studies_type = models.IntegerField(choices=((0, "Bachelor Studies"),
                                                (1, "Master Studies"),
                                                (2, "Doctoral Studies"),
                                                (3, "Integrated Studies")), default=0)
    duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
    slug = models.SlugField(max_length=140, unique=False, default=None, null=True, blank=True)

class Course(models.Model):
    study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default=None)
    name = models.CharField(max_length=50, unique=True)
    ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
    description = models.TextField()
    year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
    semester = models.IntegerField(choices=((1, "1"),
                                            (2, "2"),
                                            ), default=None)
    teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None,
                                 verbose_name="Course Teacher", related_name='%(class)s_course_teacher')
    teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True,
                                 verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher')
    slug = models.SlugField(max_length=150, unique=True)
    student = models.ManyToManyField('StudentData', default=None)
class StudentData(models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=50)
    student_ID = models.CharField(unique=True, max_length=14)
    notes = models.CharField(max_length=255, default=None, blank=True)
    enrolled = models.BooleanField(default=False)

#enroll.html

 <form action="" id="form" method=POST>
                                    {% csrf_token %}
                                    {{ form.as_p }}
                                    <input type="submit" value="Enroll">
                                </form>

如果我将null = True添加到每个字段,那就没有意义了。

1 个答案:

答案 0 :(得分:1)

这里最简单的方法就是将学生传递给模板并手动创建复选框,然后将值直接传递给课程。

def enroll_students(request, course_slug):
    course = Course.objects.get(slug=course_slug)
    if request.method == 'POST':
        course.student.add(*request.POST.getlist('student_ids'))
        return redirect('...')
    return render(request, 'enroll_students.html', {'students': StudentData.objects.all()})

...

<form action="." method="POST">
{% for student in students %}
    <label for="id_{{ student.id }}">{{ student.name }}</label>
    <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids">

{% endfor %}
<input type="submit">
</form>