Tuesday, November 28, 2017

Re: Permission for specific object in AdminPanel

Wow! That's a lot of code, please try to be more specific in order to get other people to help you. What are you trying to achieve? Autosearch of users in which context? I do not understand you :)

On Tue, Nov 28, 2017 at 6:55 AM, Allan Nava <allan.nava@ies-italia.it> wrote:
I have this admin.py and models.py

```
from django.contrib import admin

from bootcamp.groups_manager.models import Group, Member, GroupType, GroupEntity, GroupMember, GroupMemberRole
from guardian.admin import GuardedModelAdmin
class GroupAdmin(GuardedModelAdmin):
    pass

#admin.site.register(models.Group)
admin.site.register(Group, GroupAdmin)
admin.site.register(Member)
admin.site.register(GroupType)
admin.site.register(GroupEntity)
admin.site.register(GroupMember)
admin.site.register(GroupMemberRole)
```


```


class GroupMixin(GroupRelationsMixin, MPTTModel):
    name = models.CharField(max_length=255)
    codename = models.SlugField(blank=True, max_length=255)
    description = models.TextField(default='', blank=True)
    comment = models.TextField(default='', blank=True)
    parent = TreeForeignKey('self', null=True, blank=True,
                            related_name='sub_%(app_label)s_%(class)s_set')
    full_name = models.CharField(max_length=255, default='', blank=True)
    properties = JSONField(default={}, blank=True,
                            load_kwargs={'object_pairs_hook': OrderedDict})

    django_auth_sync = models.BooleanField(default=True, blank=True)
    
    #Custom permission
    background_photo = models.CharField(max_length=255, null=True, blank=True)
    profile_photo = models.CharField(max_length=255, null=True, blank=True)
    #type = models.TextField(default='', blank=True)

    class Meta:
        abstract = True
        ordering = ('name', )

    class MPTTMeta:
        level_attr = 'level'
        order_insertion_by = ['name', ]

    class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta):
        pass

    def __unicode__(self):
        return '%s' % self.name

    def __str__(self):
        return '%s' % self.name

    def save(self, *args, **kwargs):
        self.full_name = self._get_full_name()[:255]
        if not self.codename:
            self.codename = slugify(self.name, to_lower=True)
        super(GroupMixin, self).save(*args, **kwargs)

    def _get_full_name(self):
        if self.parent:
            return '%s - %s' % (self.parent._get_full_name(), self.name)
        return self.name

    @property
    def subgroups(self):
        message = 'The "subgroups" attribute will be removed in next version. ' + \
                  'Use "sub_groups_manager_group_set" instead.'
        warnings.warn(message, DeprecationWarning)
        return self.sub_groups_manager_group_set

    def get_members(self, subgroups=False):
        """Return group members.
        The result is a list of GroupsManagerMeta's attribute ``member_model`` instances.

        :Parameters:
          - `subgroups`: return also descendants members (default: `False`)
        """
        member_model = self.member_model
        group_member_model = self.group_member_model
        if group_member_model == GroupMember:
            members_relation = getattr(self, self.group_members_attribute)
            if member_model == Member:
                members = list(members_relation.all())
            else:
                # proxy model
                if member_model._meta.proxy:
                    members = list(member_model.objects.filter(
                        id__in=members_relation.values_list('id', flat=True)))
                # subclassed
                else:
                    members = list(member_model.objects.filter(
                        member_ptr__in=members_relation.all()))
        else:
            members = [gm.member for gm in group_member_model.objects.filter(group=self)]
        if subgroups:
            for subgroup in self.subgroups.all():
                members += subgroup.members
        members = list(set(members))
        return members

    @property
    def members(self):
        """Return group members. """
        return self.get_members(True)

    @property
    def users(self):
        """Return group django users. """
        users = []
        for member in self.members:
            if member.django_user:
                users.append(member.django_user)
        return users

    def get_entities(self, subgroups=False):
        """Return group entities.

        :Parameters:
          - `subgroups`: return also descendants entities (default: `False`)
        """
        entities = list(self.group_entities.all())
        if subgroups:
            for subgroup in self.subgroups.all():
                entities += subgroup.entities
            entities = list(set(entities))
        return entities

    @property
    def entities(self):
        """Return group entities."""
        return self.get_entities(True)

    def add_member(self, member, roles=None):
        """Add a member to the group.
        :Parameters:
          - `member`: member (required)
          - `roles`: list of roles. Each role could be a role id, a role label or codename,
            a role instance (optional, default: ``[]``)
        """
        print("add_member() method")
        if roles is None:
            roles = []
        if not self.id:
            raise exceptions_gm.GroupNotSavedError(
                "You must save the group before to create a relation with members")
        if not member.id:
            raise exceptions_gm.MemberNotSavedError(
                "You must save the member before to create a relation with groups")
        group_member_model = self.group_member_model
        group_member = group_member_model(member=member, group=self)
        group_member.save()
        if roles:
            for role in roles:
                if isinstance(role, GroupMemberRole):
                    group_member.roles.add(role)
                elif isinstance(role, int):
                    role_obj = GroupMemberRole.objects.get(id=role)
                    group_member.roles.add(role_obj)
                else:
                    try:
                        role_obj = GroupMemberRole.objects.get(models.Q(label=role) |
                                                               models.Q(codename=role))
                        group_member.roles.add(role_obj)
                    except Exception as e:
                        raise exceptions_gm.GetRoleError(e)
        return group_member

    def remove_member(self, member):
        """Remove a member from the group.

        :Parameters:
          - `member`: member (required)
        """
        group_member_model = self.group_member_model
        try:
            group_member = group_member_model.objects.get(member=member, group=self)
        except Exception as e:
            raise exceptions_gm.GetGroupMemberError(e)
        group_member.delete()

    def assign_object(self, obj, **kwargs):
        """Assign an object to the group.

        :Parameters:
          - `obj`: the object to assign (required)

        :Kwargs:
          - `custom_permissions`: a full or partial redefinition of PERMISSIONS setting.

        .. note::
         This method needs django-guardian.
        """
        return assign_object_to_group(self, obj, **kwargs)

    #Custom Method
    def get_picture(self):
        no_picture = django_settings.MEDIA_URL +'/group_pictures/avatar-team.jpg'
        try:
            filename = django_settings.MEDIA_ROOT + '/group_pictures/' +\
                self.user.username + '.jpg'
            picture_url = django_settings.MEDIA_URL + 'group_pictures/' +\
                self.user.username + '.jpg'
            if os.path.isfile(filename):  # pragma: no cover
                return picture_url
            else:  # pragma: no cover
                gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format(
                    hashlib.md5(self.user.email.lower()).hexdigest(),
                    urllib.urlencode({'d': no_picture, 's': '256'})
                    )
                return gravatar_url

        except Exception:
            return no_picture
    
    #Retrieve users' cover
    def get_cover(self):
        no_cover = django_settings.MEDIA_URL +'group_covers/cover.jpg'
        try:
            filename = django_settings.MEDIA_ROOT + '/group_covers/' +\
                self.user.username + '.jpg'
            cover_url = django_settings.MEDIA_URL + 'group_covers/' +\
                self.user.username + '.jpg'
            if os.path.isfile(filename) and os.path.exists(filename):  # pragma: no cover
                if cover_url != None:
                    return cover_url
                else:
                    return no_cover
            else:
                no_cover
        except Exception:
            return no_cover

class Group(GroupMixin):

    group_type = models.ForeignKey(GroupType, null=True, blank=True, on_delete=models.SET_NULL,
                                   related_name='%(app_label)s_%(class)s_set')
    group_entities = models.ManyToManyField(GroupEntity, blank=True,
                                            related_name='%(app_label)s_%(class)s_set')

    django_group = models.ForeignKey(DjangoGroup, null=True, blank=True, on_delete=models.SET_NULL)
    group_members = models.ManyToManyField(Member, through='GroupMember',
                                           related_name='%(app_label)s_%(class)s_set')

    # this is just required for easy explanation
    class Meta(GroupMixin.Meta):
        abstract = False
        permissions = (
            ('can_add_member_custom', 'Can Add Member Custom'),
            ('can_remove_member_custom', 'Can Remove Member Custom'),
            ('can_edit_group_custom', 'Can Edit Group Custom'),
        )

```
It works, but there isn't the autosearch for users, how can I implement it?



I created programmatically when the user is registered.

 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/dcbd0feb-fd33-4ff8-8219-3944514eb81d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2BFDnh%2BKNKcwP4c57k6PHScjbxJDZbpVSztLMcEKe7bNmnO6rA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment