linuxfreak linuxfreak - 2 months ago 22
Python Question

How to access request parameters from SET value of on_delete in django model

I have about 10 models each of which use User as a Foreign Key. When the user is deleted, I want to set the values in each of these tables to the one who deletes the user. The users are being deleted through django admin area by authorized staff.

So, I guess I have to call a function and use SET of on_delete method to set the value.
This is the code as per documentation.

from django.db import models
from django.contrib.auth.models import User

def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]

class MyModel(models.Model):
user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))

In my case, I want to get the user who deletes the user. That can be obtained only from Request parameters. How can I access request parameters in get_sentinel_user function?


Since a staff member is deleting other users and effectively taking ownership of the objects that belongs to the deleted user the only effective solution is to override the delete_model method in Admin.

def delete_model(self, request, obj) :
    deletes a single item.  changes ownership


Notice that the get_sentinel_user is no longer required because delete_model already has access to request.user

Howveer you are not out of the woods yet. The admin has a bulk delete action. You actually have to disable the bulk delete action for the user admin and replace it with one of your own for you to be in full control.

The “delete selected objects” action uses QuerySet.delete() for efficiency reasons, which has an important caveat: your model’s delete() method will not be called.

Please note that bulk delete does not fire any signals for each object that's deleted so the only other django based solution that works here is to override the delete method on the User manager. However the user manager will not have access to the request.user instance ether.