Can anyone help me why my formset is showing invalid when trying to update the form. It works perfectly when creating the form. The normal form is editing but the formset is not.
`def content_edit_view(request, id): course = get_object_or_404(Course, id=id) LectureFormset = modelformset_factory(Lecture, fields=('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)`