Sunday, 11 August 2013

Django Post-Save Signal

Django Post-Save Signal

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 neither assign group permissions, nor just make a test to
change the archive instance's nickname to '100' instead of whatever was
provided on the admin page at save time. How can I accomplish these
things?
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):
assign_perm('read', 'Group1', archive) #what I want to accomplish
instance.nickname = '100' #a second thing I would like to accomplish.
Also using this as a test to see if the function is being called.
instance.save()

No comments:

Post a Comment