From 7f9176f66226108d50ff484f3167d1dba66b555e Mon Sep 17 00:00:00 2001 From: Ross Date: Sun, 27 Dec 2020 18:34:17 +0000 Subject: [PATCH] . --- anatomy/forms.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/anatomy/forms.py b/anatomy/forms.py index 3c92b1f3..5d0c4b27 100644 --- a/anatomy/forms.py +++ b/anatomy/forms.py @@ -90,6 +90,43 @@ class AnatomyQuestionForm(ModelForm): queryset=Exam.objects.all(), ) + + # Only in case we build the form from an instance + # (otherwise, 'toppings' list should be empty) + if kwargs.get('instance'): + # We get the 'initial' keyword argument or initialize it + # as a dict if it didn't exist. + initial = kwargs.setdefault('initial', {}) + # The widget for a ModelMultipleChoiceField expects + # a list of primary key for the selected data. + initial['exams'] = [t.pk for t in + kwargs['instance'].exams_set.all()] + + ModelForm.__init__(self, *args, **kwargs) + + def save(self, commit=True): + # Get the unsaved Pizza instance + instance = 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.exams_set.clear() + for exam in self.cleaned_data['exams']: + instance.exams_set.add(exam) + + self.save_m2m = save_m2m + + # Do we need to save all changes now? + if commit: + instance.save() + self.save_m2m() + + return instance + class Meta: model = AnatomyQuestion