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)