Arun Karunagath
Arun Karunagath

Reputation: 1578

Django: Getting succefully deleted message even if deletion is prevented

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.

Upvotes: 2

Views: 1831

Answers (2)

Alasdair
Alasdair

Reputation: 308829

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 entire ModelAdmin.delete_view method.

If SomeModel is only used in the Django admin, another possible approach is to override the has_delete_permission method. This would remove the delete links from the change view, and disable the delete page for events in the past.

class SomeModelAdmin(admin.ModelAdmin):
    ...
    def has_delete_permission(self, request, obj=None):
        """
        Return False for events in the past
        """
        if obj is None:
            # obj is None in the model admin changelist view
            return False
        now = datetime.datetime.now()
        if obj.end < now:
            return False # past events cannot be deleted
        else:
            return super(SomeModelAdmin, self).has_delete_permission(request, obj)

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 SomeModel appears in model inlines -- although I see that has_delete_permission is an InlineModelAdmin option in Django 1.4.

Upvotes: 2

Jordan
Jordan

Reputation: 32522

You could return True or False from your overridden delete() and just work with the value of that within your form to build your message.

def delete(self, *args, **kwargs):
    now = datetime.datetime.now()
    if self.end < now:
        return False  # past events cannot be deleted

    super(SomeModel, self).delete(self, *args, **kwargs)
    return True #successfully deleted from the database

Upvotes: 0

Related Questions