.
This commit is contained in:
@@ -70,6 +70,8 @@ class RapidCreationDefaultForm(ModelForm):
|
||||
|
||||
|
||||
class RapidForm(ModelForm):
|
||||
|
||||
exams = ModelMultipleChoiceField(required=False, queryset=Exam.objects.all())
|
||||
class Media:
|
||||
# Django also includes a few javascript files necessary
|
||||
# for the operation of this form element. You need to
|
||||
@@ -106,6 +108,39 @@ class RapidForm(ModelForm):
|
||||
choices=Rapid.LATERALITY_CHOICES, required=True, widget=RadioSelect()
|
||||
)
|
||||
|
||||
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.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.clear()
|
||||
for exam in self.cleaned_data["exams"]:
|
||||
instance.exams.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 = Rapid
|
||||
# fields = ['due_back']
|
||||
|
||||
Reference in New Issue
Block a user