コード例 #1
0
def personflag_pre_save_to_group(sender, instance, raw, **kwargs):
    """
    When a personflag is created, or has it's name changed,
    update the corresponding group.
    """
    if raw:
        return  # do not change other fields in this case.
    if getattr(instance, "_sync_signal", False):
        return

    from django.contrib.auth.models import Group
    from .models import PersonFlag

    new_name = "{}".format(instance.verbose_name)
    if Group.objects.filter(name=new_name).exists():
        # existing group with the new name?  Bail now!
        return
    # everything up to here is a sanity pre-check...

    group = Group()
    if instance.pk is not None:
        # there is an old personflag, and the new group does not already exist.
        old_personflag = PersonFlag.objects.get(pk=instance.pk)
        try:
            group = Group.objects.get(name=old_personflag.verbose_name)
        except Group.DoesNotExist:
            pass

    group.name = new_name
    group._sync_signal = True
    group.save()