Reputation: 8312
I want to override a ModelForm's save() function so that it updates a field on the model if the user pressed a particular submit button. I also want to check through some other fields and update their values, and I've done this on the ModelAdmin's save_model() function. However, the save_model() function is being passed None for the object. If I comment out the form's save() function, then the save_model() function works as expected.
Is there an issue with overriding both, or have I made a mistake somewhere?
Here's a minimal example:
admin.py:
class TestAdmin(admin.ModelAdmin):
form = TestForm
def save_model(self, request, obj, form, change):
print 'test'
super(PostAdmin, self).save_model(request, obj, form, change)
admin.site.register(TestModel, TestAdmin)
forms.py:
class TestForm(forms.ModelForm):
class Meta:
model = TestModel
def save(self, force_insert=False, force_update=False, commit=True):
print 'test'
super(TestForm, self).save(commit=True)
Upvotes: 0
Views: 1581
Reputation: 118528
Your ModelForm
needs to return the instance.
As far as I remember, just prior to save_model
, the admin does a save(commit=False)
and passes the unsaved instance to save_model
. If you don't return anything, save() == None
.
return super(CategoryForm, self).save(commit=True)
Upvotes: 2
Reputation: 87205
If you are overriding the ModelAdmin.save_model
, and not calling the super().save_model
(in your example you are, I can see.), you should explicitly call the form.save()
.
If you are calling the ModelForm.save
somehow, through super or explicit calling, I don't see why it wouldn't work; but I can tell you that if I were to override the save_model
, my preference would be to limit myself to overriding the Model.save()
.
Upvotes: 0