python 如何使用非表单数据填充模型?

z9zf31ra  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(122)

我有Student、Class和StudentClass模型。我希望学生能够通过在表单中输入class_code来加入一个新的班级。要加入一个班级,用户的student_id和class_code被保存到StudentClass模型中。student_id不是一个表单字段,因此应该通过用登录用户的用户名查询Student模型并返回student_id来获得。
models.py:

class StudentClass(models.Model):
    class Meta:
        unique_together = (('class_code', 'student_id'),)
    class_code = models.ForeignKey(Class, on_delete=models.CASCADE)
    student_id = models.ForeignKey(Student, on_delete=models.CASCADE)

forms.py:

class JoinClassForm(forms.ModelForm):
    class Meta:
        model = StudentClass
        fields = ['class_code']

views.py

@login_required
def join_class(request):
    if request.method == "POST":
        joinclass_form = JoinClassForm(request.POST or None)
        if joinclass_form.is_valid():
            formclass_code = joinclass_form.data.get('class_code')
            if Class.objects.filter(class_code=formclass_code).exists():
                joinclass_form.save(commit=False)
                joinclass_form.student_id =
                Student.objects.filter(username=request.user.username).values_list('student_id', flat=True)
                joinclass_form.save()
                return redirect('assignments')
            else:
                messages.success(request, ("This class doesn't exist!"))
    else:
        joinclass_form = JoinClassForm
    return render(request, 'join_class.html', {'joinclass_form': joinclass_form})

我试过对student_id使用hidden_field,从表单字段中排除student_id并保存为commit=False,但我得到了同样的错误:IntegrityError Not NULL条件约束失败。我的程式码中是否有遗漏的错误,或是我使用了错误的方法?预先感谢
编辑:请原谅我,但是复制粘贴在最后一组代码上出了点问题,我不知道如何修复它

bf1o4zei

bf1o4zei1#

您不需要将**.username放在request.user处。您可以只说request.user**

相关问题