gpt4 book ai didi

python - BooleanField 未更新 : Django

转载 作者:行者123 更新时间:2023-12-01 08:29:09 26 4
gpt4 key购买 nike

我正在通过构建一个示例应用程序来学习 Django,学生可以在其中选择参与学习部分。参与操作是一个 bool 字段,我希望学生能够选中或取消选中并更新它。默认情况下它是未选中的,我可以选中它并保存表单。但是当我去更新表单时,该框未被选中。如何设置表单、模型和 View 以便保存和更新参与字段?

模型.py

class StudentAnswer(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='study_answers')
study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='study_participate', null=True)
participate = models.BooleanField('Participate?', default=False)

表单.py

class ViewStudyForm(forms.ModelForm):

class Meta:
model = StudentAnswer
fields = ('participate', )

View .py

@login_required
@student_required
def participate_study(request, pk):
study = get_object_or_404(Study, pk=pk)
student = request.user.student

total_details = study.details.count()
details = student.get_details(study)

if request.method == 'POST':
form = ViewStudyForm(data=request.POST)
if form.is_valid():
with transaction.atomic():
student_answer = form.save(commit=False)
student_answer.student = student
student_answer.save()
messages.success(request, 'Congratulations! You signed up to participate in the study %s!' % (study.name))
return redirect('students:study_list')
else:
form = ViewStudyForm()
progress=100
return render(request, 'classroom/students/past_study_form.html', {
'study': study,
'details': details,
'form': form,
'progress': progress
})

最佳答案

尝试这样的事情:

....
else:
participate = StudentAnswer.objects.get(student=student).values('participate')
form = ViewStudyForm(initial={'participate': participate})

这应该从您的 StudentAnswer 实例中获取 bool 值 participate 并将其分配给您的表单。
更多信息请参见 Django docs .

关于python - BooleanField 未更新 : Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com