Django Assign-perm w/ Post-Save Signal

前提是你 提交于 2019-12-25 05:25:16

问题


I have a django model named archive that is tied to a group (django auth) by a foreign key. In order for a user to edit something in this archive, they must have permission to do so through django-guardian. I can link an archive with a group as shown in my code below, however, I need to be able to set per-object (archive)-permissions with each group as well. I am seeking to do this using a post_save or post_delete signal (to properly prevent orphan permissions).

In other words, here are the steps I want to accomplish. Visit Admin page. Create/Edit an instance of Archive. Specify on that page what user-group will be associated with that particular Archive. Upon saving that instance, Django should automatically authenticate the specified group with 'read' permissions for that instance of Archive.

What file would I store Archive_post_save_handler in? models.py? As it stands, I can't assign group permissions because I think I am having trouble passing objects through my functions. How can I accomplish this? As a bonus question, will this hook also apply if I edited the model through a shell?

models.py

from django.db import models
from django.contrib.auth.models import Group
from django.db.models.signals import *
from django.dispatch import receiver

class Archive(models.Model):
    name = models.CharField(max_length = 30)
    nickname = models.CharField(max_length = 30, blank=True)
    Group = models.ForeignKey(Group, blank=True, null=True, help_text='A group of users that are allowed access to the archive. This should typically be called the same thing as the archive name.')

    class Meta:
        permissions = (
            ('read', 'Read Archive'),
        )

    def __unicode__(self):
        return self.name

@receiver(post_save, sender=Archive)
def Archive_post_save_handler(sender, instance, **kwarks):
    group = Group.objects.get(name=instance.Group)
    assign_perm('read', group, instance) #what I primarily want to accomplish in this question is on this line

回答1:


I think the code you pasted here will cause a recursive calling Archive_post_save_handler, because the last line of code will also trigger another post_save signal. You should get the created argument from the kwargs to test if the instance is created for the first time.



来源:https://stackoverflow.com/questions/18178978/django-assign-perm-w-post-save-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!