我正在尝试将一个复选框添加到表单,如果为true,我希望它向manytomanyfield的贯穿模型添加一行,但是我无法访问该复选框变量。这是我添加到的表单,它按预期出现,所以只有一半:
class ProjectUpdateForm(forms.ModelForm):
completed = forms.BooleanField(). # this variable here
class Meta:
model = Update
fields = [
'category',
'update'
]
我认为我希望对此进行处理:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(f"================{form.completed}") # attempt to find variable
form.save()
return redirect('project-list')
else:
form = ProjectUpdateForm()
context = {
"form": form,
"object": obj
}
return render(request, 'project_portal/project_update.html', context)
这给我标题中的错误。所以我现在不明白什么是属性,我认为这是变量代表的类的一个方面。如何访问此复选框变量,以便可以使用它?
答案 0 :(得分:1)
它的格式为cleaned_data
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(form.cleaned_data['completed'])
form.save()
return redirect('project-list')