문제

I am really having troubles getting my Admin-interface working. I have a Model and within that model a m2m-field to Group:

from django.contrib.auth.models import Group

class Lecture(models.Model):
   ....
   allowed_groups = models.ManyToManyField(Group)
   ....

Now, when the model is saved I want to give those groups special viewing-rights, so that only members of those groups are allowed to see objects of that model. I use django-guardian for per object permissions. So in the save-method of my model I do something like that:

def save(self, *args, **kwargs):
    allGroups = Group.objects.all() 
    super(Lecture, self).save(*args, **kwargs)
    groups = self.allowed_groups.all()       

    viewright = 'view_lecture'

    for ag in allGroups:
        if ag in groups:               
            assign_perm(viewright, ag, self) #assign_perm comes from guardian
        else:                
            remove_perm(viewright, ag, self) #remove_perm comes from guardian

I also tried to use a post_save signal, but the problem is, that I always have press the save button in my admin-interface twice to make any changes happen (The Groups are always added in the right way but the permissions are only added on the second time the model is saved via save button in the admin interface ) So what is going on here? Can anybody help?

--- EDIT ---

My Solution: I moved the permission-assignment-code to my ModelAdmin class, like that:

admin.py

class LectureAdmin(admin.ModelAdmin):            


def save_model(self, request, lecture, form, change):
    if not lecture.id:
        lecture.owner = request.user        

    super(LectureAdmin, self).save_model(request, lecture, form, change)        
    allGroups = Group.objects.all()
    groups = form.cleaned_data['allowed_groups']

    viewright = 'cms.view_lecture'

    for ag in allGroups:
        if ag in groups:                         
            assign_perm(viewright, ag, lecture)

        else:                                  
            remove_perm(viewright, ag, lecture) 
도움이 되었습니까?

해결책

You need to define a save_m2m method on your admin form and perform your custom relationship-building there, rather than trying do this in the model's save method. The reason for this is because the model admin adds a save_m2m method to your model form and calls it after calling save on your model form, setting the m2m relations to the selections in the form (the value of which is presumably empty upon that first save).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top