Fakultas Ilmu Komputer UI

views.py 1.16 KB
Newer Older
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from rest_framework import viewsets, status
from rest_framework.response import Response
from dietela_quiz.models import DietProfile
from dietela_quiz.serializers import DietProfileSerializer
from .models import CustomUser
from .serializers import CustomUserDetailsSerializer


class LinkUserAndDietProfileViewSet(viewsets.ViewSet):

    @staticmethod
    def create(request):
        email = request.data['email']
        diet_profile_id = request.data['diet_profile_id']

        try:
            user = CustomUser.objects.get(email=email)
        except CustomUser.DoesNotExist:
            return Response({'message': 'User is not found.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            diet_profile = DietProfile.objects.get(id=diet_profile_id)
        except DietProfile.DoesNotExist:
            return Response({'message': 'Diet profile is not found.'}, \
                status=status.HTTP_400_BAD_REQUEST)

        user.diet_profile = diet_profile
        user.save()

        return Response({\
            'user': CustomUserDetailsSerializer(user).data,\
            'diet_profile': DietProfileSerializer(diet_profile).data\
        }, status=status.HTTP_200_OK)