Python Django Authentication Users and Authorization Bringing It All Together

Chris Komaroff
PRO
Chris Komaroff
Pro Student 13,659 Points

Here is code for ChangeStatus view - copied from video, seems to work for me.

communities\views.py
class ChangeStatus(
    LoginRequiredMixin,
    PermissionRequiredMixin,
    generic.RedirectView
):
    permission_required = "communities.ban_member"

    # View requires "communites.ban_member" except for admins 
    def has_permission(self):
        return any([
            super().has_permission(),
            self.request.user.id in self.get_object().admins
        ])

    # ChangeStatus view based on Community model instance for slug
    def get_object(self):
        return get_object_or_404(
            models.Community,
            slug = self.kwargs.get("slug")
        )

    def get_redirect_url(self, *args, **kwargs):
        return self.get_object().get_absolute_url()

    # HTTP get()
    def get(self, request, *args, **kwargs):
        role = int(self.kwargs.get("status"))
        membership = get_object_or_404(
            models.CommunityMember,
            community__slug = self.kwargs.get("slug"),
            user__id = self.kwargs.get("user_id")
        )
        membership.role = role
        membership.save()

        try:
            moderators = Group.objects.get(name__iexact="moderators")
        except Group.DoesNotExist:
            moderators = Group.objects.create(name="Moderators")
            moderators.permissions.add(
                Permission.objects.get(codename="ban_member")               
            )

        if role in [2, 3]:
            membership.user.groups.add(moderators)
        else:
            membership.user.groups.remove(moderators)

        messages.success(request, "@{} is now {}".format(
            membership.user.username,
            membership.get_role_display()
        ))

        return super().get(request, *args, **kwargs)