开发者

Django - Models - overriding delete()

开发者 https://www.devze.com 2023-01-24 04:41 出处:网络
I just need t开发者_Python百科o send a mail notification whenever a model is deleted. I can achieve this by overriding delete() method. But, the notification mail should specifies the current user who

I just need t开发者_Python百科o send a mail notification whenever a model is deleted. I can achieve this by overriding delete() method. But, the notification mail should specifies the current user who actually deleted this model. Is there any way to get the current user inside delete() method?


  1. The correct way to hook generically in to events such as deletion is to use signals and NOT to override the delete method: https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_delete
  2. In both cases you cannot get the user, because there may be no user, as when deletion happens from a console, or in some other manner
  3. if you need to deal with user-triggered deletes, the solution is to restrict deletion to only occurring in views, and wrapping those views to deal with deletion in whatever way is appropriate for your application.


You might want to do this in a view, so you've got access to the user. For example:

def my_view(request):
    # Send an e-mail containing request.user
    object = Model.objects.get(id=123)
    object.delete()
0

精彩评论

暂无评论...
验证码 换一张
取 消