This commit is contained in:
Ross
2020-12-27 18:50:57 +00:00
parent 7f9176f662
commit 7f43d50781
+14 -10
View File
@@ -39,6 +39,10 @@ class MarkAnatomyQuestionForm(Form):
class AnatomyQuestionForm(ModelForm): class AnatomyQuestionForm(ModelForm):
exams = ModelMultipleChoiceField(queryset=Exam.objects.all())
class Media: class Media:
# Django also includes a few javascript files necessary # Django also includes a few javascript files necessary
# for the operation of this form element. You need to # for the operation of this form element. You need to
@@ -85,10 +89,10 @@ class AnatomyQuestionForm(ModelForm):
queryset=BodyPart.objects.all(), queryset=BodyPart.objects.all(),
) )
self.fields["exams"] = ModelChoiceField( #self.fields["exams"] = ModelChoiceField(
required=False, # required=False,
queryset=Exam.objects.all(), # queryset=Exam.objects.all(),
) #)
# Only in case we build the form from an instance # Only in case we build the form from an instance
@@ -100,7 +104,7 @@ class AnatomyQuestionForm(ModelForm):
# The widget for a ModelMultipleChoiceField expects # The widget for a ModelMultipleChoiceField expects
# a list of primary key for the selected data. # a list of primary key for the selected data.
initial['exams'] = [t.pk for t in initial['exams'] = [t.pk for t in
kwargs['instance'].exams_set.all()] kwargs['instance'].exams.all()]
ModelForm.__init__(self, *args, **kwargs) ModelForm.__init__(self, *args, **kwargs)
@@ -114,16 +118,16 @@ class AnatomyQuestionForm(ModelForm):
def save_m2m(): def save_m2m():
old_save_m2m() old_save_m2m()
# This is where we actually link the pizza with toppings # This is where we actually link the pizza with toppings
instance.exams_set.clear() instance.exams.clear()
for exam in self.cleaned_data['exams']: for exam in self.cleaned_data['exams']:
instance.exams_set.add(exam) instance.exams.add(exam)
self.save_m2m = save_m2m self.save_m2m = save_m2m
# Do we need to save all changes now? # Do we need to save all changes now?
if commit: #if commit:
instance.save() instance.save()
self.save_m2m() self.save_m2m()
return instance return instance