python - How to access request parameters from SET value of on_delete in django model -
i have 10 models each of use user foreign key. when user deleted, want set values in each of these tables 1 deletes user. users being deleted through django admin area authorized staff.
so, guess have call function , use set of on_delete method set value. code per documentation.
from django.db import models 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 case, want user deletes user. can obtained request parameters. how can access request parameters in get_sentinel_user function?
since staff member deleting other users , taking ownership of objects belongs deleted user effective solution override delete_model method in admin.
def delete_model(self, request, obj) : ''' deletes single item. changes ownership ''' mymodel.objects.filter(user_id=obj.pk).update(user_id=request.user.id) obj.delete()
notice get_sentinel_user no longer required because delete_model has access request.user
howveer not out of woods yet. admin has bulk delete action. have disable bulk delete action user admin , replace 1 of own in full control.
the “delete selected objects” action uses queryset.delete() efficiency reasons, has important caveat: model’s delete() method not called.
please note bulk delete not fire signals each object that's deleted other django based solution works here override delete method on user manager. user manager not have access request.user instance ether.
Comments
Post a Comment