Reputation: 363
I am learning Django by building an example app in which students can choose to participate in study sections. The participate action is a BooleanField that I would like the students to be able to check or uncheck and update. It is unchecked by default and I am able to check it and save the form. But when I go to update the form the box is unchecked. How can I set up the form, model, and view so that the participate field can be saved and updated?
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
})
Upvotes: 1
Views: 468
Reputation: 2671
Try something like this:
....
else:
participate = StudentAnswer.objects.get(student=student).values('participate')
form = ViewStudyForm(initial={'participate': participate})
This should take boolean participate
from your StudentAnswer instance and assign it to your form.
More informations is here in Django docs.
Upvotes: 1