1

I want my projects to have one leader with lead_project permission for individual projects. This Leader is stored as a ForeignKey in the Project class. In my custom ProjectAdmin I managed to assign the permission by defining save_model.

class ProjectAdmin(GuardedModelAdmin):
    ...
    def save_model(self, request, obj, form, change):
            leaderid = obj.get_projectLeaderid()
            project = Project.objects.get (name=obj)
            newleader = AbstractUser.objects.get (id=leaderid)
            assign_perm("lead_project", newleader, project)
            obj.save()

My Project class:

class Project (models.Model):
    name = models.CharField(max_length=1000)
    projectLeader = models.ForeignKey('anmeldung.AbstractUser', blank=True, null=True, )
    ...
    class Meta:
        permissions = (
            ("view_project", "Has permission to view this project"),
            ("lead_project", "Is Projectleader"), #Nur ProjecLeader
        )

I am using django-guardian for object permission, Assign_perm is one of its shortcuts. I thought of using remove_perm (also a django-guardian shortcut), but i need the ID of the "old" user.

Question: How do i get the ID of the old user or in general, the former value of a field.

Rubick
  • 139
  • 3
  • 11
  • `project` and `obj` should be the same model instance. But since obj has not been saved yet, `project` should be the old version since it is fetched form the db. So you could try `project.get_projectLeaderid()`. – user2390182 Jan 16 '18 at 10:43
  • Thanks, it worked perfectly! – Rubick Jan 16 '18 at 11:00
  • Cheers :) btw, I don't know what code is in that method, but django provides the fk id directly in `project.projectLeader_id` – user2390182 Jan 16 '18 at 11:05
  • Thanks for the hint. The problem is if no projectleader is selected (which happens while creating the Project) i get `AbstractUser matching query does not exist.` My method returns the id`if not None`, otherwise it returns `0`, which i use for `if oldleaderid is not 0:` – Rubick Jan 16 '18 at 11:47

0 Answers0