Fakultas Ilmu Komputer UI

Verified Commit 203f8f32 authored by Giovan Isa Musthofa's avatar Giovan Isa Musthofa
Browse files

[GREEN] Add UserProfileView and it's serializer

parent 0d102fc7
Pipeline #38404 passed with stages
in 7 minutes and 14 seconds
......@@ -108,3 +108,34 @@ class RegistrationFullSerializer(RegistrationSerializer):
'required': True
},
}
class UserProfileSerializer(ModelSerializer):
profile = ProfilePartialSerializer()
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.save()
# Handle nested instance
profile = instance.profile
for field in ('body_weight', 'id_card_no', 'birthplace', 'birthdate', 'sex',
'profession', 'blood_type', 'married_status', 'address',
'city', 'district', 'village', 'phone_no', 'work_address',
'work_email', 'work_phone_no'):
value = profile_data.get(field, getattr(profile, field))
setattr(profile, field, value)
profile.save()
return instance
class Meta:
model = User
fields = ('email', 'first_name', 'profile')
extra_kwargs = {
'email': {
'read_only': True
},
}
......@@ -10,11 +10,13 @@ from .views import (
RegisterFullView,
RegisterView,
SecretView,
UserProfileView,
)
urlpatterns = [
path('hello/', HelloView.as_view()),
path('secret/', SecretView.as_view()),
path('user/profile/', UserProfileView.as_view()),
path('auth/register/', RegisterView.as_view()),
path('auth/register-full/', RegisterFullView.as_view()),
path('auth/access/', AccessTokenView.as_view()),
......
......@@ -4,7 +4,7 @@ from django.http import HttpResponseRedirect
from django.shortcuts import reverse
from django.template.loader import render_to_string
from rest_framework import generics
from rest_framework import views
from rest_framework import status, views
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from urllib.parse import urljoin
......@@ -208,3 +208,26 @@ class OAuthAccessTokenView(views.APIView):
break
return userinfo
class UserProfileView(generics.RetrieveUpdateAPIView):
serializer_class = serializers.UserProfileSerializer
permission_classes = [IsAuthenticated]
def get(self, request, *args, **kwargs):
serializer = self.serializer_class(instance=request.user)
return Response(serializer.data)
def put(self, request, *args, **kwargs):
serializer = self.serializer_class(instance=request.user,
data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.error_messages,
status=status.HTTP_400_BAD_REQUEST)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment