python - BooleanField 未更新 : Django

标签 python django

我正在通过构建一个示例应用程序来学习 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/

相关文章:

python - 通过我的 Django 模型访问选择

python - 如何使用 wsdl 文件创建异步 zeep 客户端?

c# - 如何使 C# 构造函数语法更像 pythonic?

Python:使用已知字符制作暴力哈希检查器

django - 以编程方式创建Django组

django - 我在哪里放置代码以将数据从数据库推送到 django-redis 的 redis?

Django - 带有 django-celery-beat/rabbitmq : Nothing? 的 Celery 4.1

python - 类没有对象成员

python - 表单清理方法与模型清理方法与模型字段验证器

python - 使用 __getattr__(self, name) 访问实例的其他属性