我正在通过构建一个示例应用程序来学习Django,学生可以在其中选择参加学习部分。参与动作是一个BooleanField,我希望学生能够选中或取消选中和更新。默认情况下未选中它,我能够对其进行检查并保存表格。但是,当我去更新表格时,该框未选中。如何设置表单,模型和视图,以便可以保存和更新参与字段?
models.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)
forms.py
class ViewStudyForm(forms.ModelForm):
class Meta:
model = StudentAnswer
fields = ('participate', )
views.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
})
答案 0 :(得分:1)
尝试这样的事情:
....
else:
participate = StudentAnswer.objects.get(student=student).values('participate')
form = ViewStudyForm(initial={'participate': participate})
这应该从您的StudentAnswer实例中获取布尔值participate
并将其分配给您的表单。
更多信息在Django docs中。