[Fixed]-Multiple forms submitting with single view – Django

1👍

Solution:

Instead of using the instance argument, use prefix:

def IndexView(request,Course_id,Section_id):
    if request.method == "GET":

        this_course = Course.objects.get(pk=Course_id)
        active_courses = Course.objects.all().filter(Active=True).exclude(pk=Course_id)
        section_list = Section.objects.all().filter(course=this_course)
        if len(section_list) >1:
            multi_section = True
        else:
            multi_section = False
        active_section = Section.objects.get(pk=Section_id)
        roster = Student.objects.all().filter(sections__in=[active_section])
        announcement_list = Announcement.objects.all().filter(sections__in=[active_section])
        courseaddform = CourseAddForm(prefix='crs')
        sectionaddform = SectionAddForm(prefix='sctn')

        context = {'active_courses':active_courses, 'this_course': this_course,
                   'active_section':active_section, 'section_list':section_list,
                   'roster':roster, 'multi_section':multi_section,
                   'announcement_list':announcement_list, 'courseaddform':courseaddform,
                   'sectionaddform':sectionaddform}
        return render(request,'gbook/index.html', context)
    elif request.method == "POST":
        this_course = Course.objects.get(pk=Course_id)
        active_courses = Course.objects.all().filter(Active=True).exclude(pk=Course_id)
        section_list = Section.objects.all().filter(course=this_course)
        if len(section_list) >1:
            multi_section = True
        else:
            multi_section = False
        active_section = Section.objects.get(pk=Section_id)

        f = CourseAddForm(request.POST, prefix='crs')
        g = SectionAddForm(request.POST, prefix='sctn')
        if f.is_valid() and g.is_valid():
            new_course = f.save()
            new_section = g.save(commit=False)
            new_section.course = new_course
            print new_section.course
            new_section.save()

        return redirect("/gbook/"+str(Course_id)+"/"+str(active_section))
👤DeltaG

0👍

Both models have a Name field, so both forms contain an input with identical name attribute. When Django encounters two POST parameters with the same name, it binds the last one’s value to all fields by that name. Long story short – change field names in your models so they are different.

0👍

Since your Course and Section both have an attribute called Name, I am betting that your form has two fields with the attributes id = "id_Name" and name = "Name".

Leave a comment