class SomeModel(models.Model):
end = models.DateTimeField()
def delete(self, *args, **kwargs):
now = datetime.datetime.now()
if self.end < now:
return # past events cannot be deleted
super(SomeModel, self).delete(self, *args, **kwargs)
I’ve wrote above code in one of my models.
It’s working beautifully but having one single problem:
I’m getting a message saying, object is successfully deleted even if that model is not deleted because if the condition I put in.
Is there a way I can send a message that object is not deleted in this case?
NB: This model is for django-admin only.
The delete view in the django admin does not check to see if the
delete()call was successful, so if you want to override the delete method as in your question, you’ll need to override the entireModelAdmin.delete_viewmethod.If
SomeModelis only used in the Django admin, another possible approach is to override thehas_delete_permissionmethod. This would remove the delete links from the change view, and disable the delete page for events in the past.The implementation above would disable the “delete selected objects” admin action, as we return False when obj is None. You should consider doing this anyway, as it calls the queryset delete method and not your overridden delete method.
With this approach, superadmins would still be able to delete events as they have all permissions. I don’t think this approach would work if
SomeModelappears in model inlines — although I see thathas_delete_permissionis anInlineModelAdminoption in Django 1.4.