Reputation: 376
In a library system, I have the Userbooks (refers to books issued by a user) object registered with Django Admin. And when Django Admin creates a Userbooks object and saves it, the Book object (refers to books in library, also registered with Django Admin) associated with that UserBook with a one_to_one relationship, needs to have its boolean field 'is_issued' to be set to true. How can I do this backend action when Admin clicks the 'save' button?
Upvotes: 0
Views: 1509
Reputation: 347
In the question you specifically asked that this action should happen when the admin tries to save it from admin. The solution suggested by @pansul-bhatt does the same thing on Model save. Even the alternative(Handling pre-save signal) would do the same thing. So even if you save the model from anywhere else in the code you will set is_issued
as True
.
The better way to do it is to override the save_model on the UserbooksAdmin.
class UserBookAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.is_issued = True
obj.save()
This should be enough to solve your problem. But there are other hooks available with Django Admin.
Upvotes: 1
Reputation: 394
My suggestion would be to either you use pre save signals or just override the save method to do whatever operation use want
class ModelB(models.Model):
def save(self):
# add logic to change is_issue value to True
super(ModelB, self).save()
Hope this helps.
Upvotes: 3