I have an AdminModel that allows users to save with any of the fields left empty. However, I don’t want them to be able to save when all fields are empty. I’ve implemented this using the following:
def save_model(self, request, obj, form, change):
if form.has_changed():
obj.save()
else:
pass
However, the Model has a M2M relationship with another Model, so I get the following error when I hit save:
instance needs to have a primary key value before a many-to-many relationship can be used.
What do I need to add to this method to stop it trying to create the M2M relationship?
Edit:
I’ve added hacky workaround, but I’d be interested in knowing if there’s a better way of doing it. The workaround was to change the else so it changes the ModelAdmin’s field attribute so that it doesn’t contain the field for the M2M relationship – this prevents it from trying to make the relationship. This is not only hacky, but also only works after it’s failed to save the model once and thrown an error…
You can’t –
save_m2mis called aftersave_model. The docs specifically say this hook is not for veto purposes.What you need is form validation to prevent
save_modelfrom triggering. Somehow, you need to detect when all fields are left blank.