djangopython-3.xdjango-admindjango-guardian

code in save_model executed on second save, not first


i defined a save_model in my UserAdmin to change object level permissions for users.

class UserAdmin(BaseUserAdmin):

    def save_model(self, request, obj, form, change):

        obj.save()
        allprojects = Project.objects.all()
        projects = obj.workingproject.all()
        remove_perm("view_project", obj, allprojects)
        assign_perm("view_project", obj, projects)
        obj.save()

remove_perm and assign_perm are shortcuts from django-guardian, workingproject is a M2M field of user.

The problem: when selecting different projects and saving the permissions are not changed, but pressing the save button a second time makes the changes as wanted. What am i doing wrong?


Solution

  • Try this by overriding save_related

    def save_related(self, request, form, formsets, change):
        super(UserAdmin, self).save_related(request, form, formsets, change)
        obj = form.instance
        allprojects = Project.objects.all()
        projects = obj.workingproject.all()
        remove_perm("view_project", obj, allprojects)
        assign_perm("view_project", obj, projects)
    

    In save_related, Django is removing M2M that are already there and setting new ones. So changes doing in save_model and save will not reflect.