任何人都可以帮助我,为什么我的表单集在尝试更新表单时显示为无效。创建表单时,它可以完美地工作。普通表单正在编辑,但表单集不是。
`def content_edit_view(请求,ID): 路线= get_object_or_404(课程,id = id) LectureFormset = modelformset_factory(讲座,字段=('lecture_title','lecture_content','youtube_url'),extra = 0)
if course.user != request.user:
raise Http404()
if request.method == 'POST':
content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course)
formset = LectureFormset(request.POST or None, request.FILES or None)
if content_edit_form.is_valid():
content_edit_form.save()
data = Lecture.objects.filter(course=course)
# give index of the item for a formset item strting form 0 and (f)the item itself
if formset.is_valid():
for index, f in enumerate(formset):
if f.cleaned_data:
if f.cleaned_data['id'] is None:
video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
video.save()
else:
video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded
d.lecture_title = video.lecture_title # changing the database tiitle with new title
d.lecture_content = video.lecture_content #changing the database content with new content
d.youtube_url = video.youtube_url # changing the database content with new content
d.save()
return redirect('teacher-profile')
else:
print('formset is invalid')
else:
print("form is invalid")
else:
content_edit_form = ContentEditForm(instance=course)
formset = LectureFormset(queryset=Lecture.objects.filter(course=course))
context = {
'contentForm': content_edit_form,
'course': course,
'formset': formset,
}
return render(request, 'apps/contentEdit.html', context)`