Skip to content
Snippets Groups Projects
  • Andreas Ellewsen's avatar
    701afd23
    Add role adding page to guest profiles · 701afd23
    Andreas Ellewsen authored
    Code for guest routes moved to their own folder so that we don't need
    multiple api calls.
    Serializer class for roles has been simplified with methods for
    validation of each field and a separate one used in invites without
    requiring the person field.
    
    Resolves: GREG-61
    Add role adding page to guest profiles
    Andreas Ellewsen authored
    Code for guest routes moved to their own folder so that we don't need
    multiple api calls.
    Serializer class for roles has been simplified with methods for
    validation of each field and a separate one used in invites without
    requiring the person field.
    
    Resolves: GREG-61
role.py 1.77 KiB
from django.db import transaction
from rest_framework import serializers, status
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from greg.models import Role
from greg.permissions import IsSponsor
from gregui.api.serializers.role import RoleSerializerUi
from gregui.models import GregUserProfile


class RoleInfoViewSet(ModelViewSet):
    queryset = Role.objects.all()
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated, IsSponsor]
    serializer_class = RoleSerializerUi

    def partial_update(self, request, pk):
        role = Role.objects.get(pk=pk)
        sponsor = GregUserProfile.objects.get(user=self.request.user).sponsor
        with transaction.atomic():
            serializer = self.serializer_class(
                instance=role,
                data=request.data,
                partial=True,
                context={"sponsor": sponsor},
            )
            serializer.is_valid(raise_exception=True)
            instance = serializer.update(role, serializer.validated_data)
            instance.save()
        return Response(status=status.HTTP_200_OK)

    def create(self, request):
        sponsor = GregUserProfile.objects.get(user=self.request.user).sponsor
        with transaction.atomic():
            serializer = self.serializer_class(
                data=request.data,
                context={
                    "sponsor": sponsor,
                },
            )
            serializer.is_valid(raise_exception=True)
            serializer.save(sponsor=sponsor)
        return Response(status=status.HTTP_201_CREATED)