[Answered ]-Unable to update a Class Model in Django

1👍

You need to pass an instance to the form if you want to update the existing db entry but not to create a new one.

instance = Class.objects.get(some parameters here)
form = ClassForm(instance=instance)

1👍

I think you just need to add instance.save() after updating the many to many field.

if form.is_valid():
        # Never enter this part of the form because form never validates

        callNumber = form.cleaned_data.get("callNumber")
        course = Class.objects.filter(pk = callNumber)
        print course 
        print request.user 
        print course.Student_List.add(request.user)
        print course 
        print "I added a student to the class"



        callNumber = form.cleaned_data.get("callNumber")
        print callNumber, "is the call number"

        course = get_object_or_404(Class, pk=callNumber)
        Class.User.add(request.user)
        # print course
        #I think this should do the trick.
        course.save()
        return redirect('/user-course-status/')

Being noob to django myself, I m not sure this is what you were looking for.

0👍

The answer given by @chem1st is correct, change the below code

your code

form = ClassForm(request.POST or None)

replace with this code

form = ClassForm(request.POST or None, instance=request.user)

if you wan’t to show the existing data of that user in you form use this code

data = {
    'callNumber': user.callNumber,
    '**extra_fields**': user.**extra_fields**,
}
form = ClassForm(request.POST or None, instance=request.user, initial=data)

Leave a comment