Save Many-To-Many Field Django Forms

后端 未结 1 482
你的背包
你的背包 2020-12-17 07:03

I have a Many-To-Many relationship between a Course and Tutor model. I am trying to make it so that when you use a form to create a record for a new Tutor, you can select th

1条回答
  •  隐瞒了意图╮
    2020-12-17 07:47

    Updated answer

    The problem is in save method. You save instance with commit=False but your instance saved when if commit: so it's not saving now.

    Just commented out if commit: and it will be saved well.

    def save(self, commit=True):
        # Get the unsaved Pizza instance
        instance = forms.ModelForm.save(self, False)
    
        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m
    
        def save_m2m():
            old_save_m2m()
            # This is where we actually link the pizza with toppings
            instance.course_set.clear()
            for course in self.cleaned_data['courses']:
                instance.course_set.add(course)
    
        self.save_m2m = save_m2m
    
        # Do we need to save all changes now?
        # Just like this
        # if commit:
        instance.save()
        self.save_m2m()
    
        return instance
    

    0 讨论(0)
提交回复
热议问题