I'm using the Django admin and trying to make some changes to a related object that is mapped as an InlineModelAdmin object. I'm trying to do this using the save_related(self, request, form, formsets, change) method that Django provides. When I try to save something, I get an error:
AttributeError: 'AlumniResponseFormFormSet' object has no attribute 'new_objects'
1) I have two InlineModelAdmins
2) I'm not saving the AlumniResponseInline when this error occurs. I'm saving another InlineModelAdmin associated with the same parent model
3) Until I added the save_related() method, I wasn't having problems saving either InlineModelAdmin
4) This error is happening after all my code is executed in save_related(), so I don't have control over catching that exception
From the documentation on save_related():
The save_related method is given the HttpRequest, the parent ModelForm instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed. Here you can do any pre- or post-save operations for objects related to the parent. Note that at this point the parent object and its form have already been saved.
I use save_formset instead of save_related and I was having the same problem until I realized that I missed two important lines inside the method:
instances = formset.save(commit=False)
at the beginning, and then, after loop instances to do something with each instance:
instance.save() #commit instance changes
formset.save_m2m() #commit the whole formset changes
at the end.
If you don't call the save_m2m() method before return, the formset object won't have the 'new_objects' attribute, needed in the construct_change_message(self, request, form, formsets)
method in contrib/admin/options.py
So, this should be done for every inline you have in the main model, no matter whether you want to make something with it or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With