ft_transcendence/profiles/viewsets.py

62 lines
2.6 KiB
Python
Raw Permalink Normal View History

2023-12-06 09:19:41 -05:00
from rest_framework import permissions
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import permissions, status
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
2023-12-06 09:19:41 -05:00
2023-12-06 10:48:21 -05:00
from django.http import HttpRequest
2023-12-06 09:19:41 -05:00
from django.db.models import QuerySet
from .serializers import ProfileSerializer
from .models import ProfileModel
class ProfileViewSet(viewsets.ModelViewSet):
queryset = ProfileModel.objects.all
2023-12-06 09:19:41 -05:00
serializer_class = ProfileSerializer
parser_classes = (MultiPartParser, FormParser)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
2023-12-06 10:48:21 -05:00
def retrieve(self, request: HttpRequest, pk=None):
2023-12-17 14:29:04 -05:00
if (not self.queryset().filter(pk=pk).exists()):
2023-12-17 14:27:13 -05:00
return Response({"detail": "Profile not found."}, status=status.HTTP_404_NOT_FOUND)
instance = self.queryset().get(pk=pk)
2023-12-09 15:51:32 -05:00
instance.avatar_url.name = instance.avatar_url.name[instance.avatar_url.name.find("static") - 1:]
2023-12-06 10:48:21 -05:00
return Response(self.serializer_class(instance).data,
status=status.HTTP_200_OK)
2023-12-09 15:51:32 -05:00
def list(self, request: HttpRequest):
serializer = ProfileSerializer(self.queryset(), many=True)
2023-12-09 15:51:32 -05:00
for profile in serializer.data:
profile["avatar_url"] = profile["avatar_url"][profile["avatar_url"].find("static") - 1:]
return Response(serializer.data)
2023-12-08 11:36:41 -05:00
2023-12-06 09:19:41 -05:00
def perform_create(self, serializer):
serializer.save(user=self.request.user)
2023-12-16 12:00:38 -05:00
class MyProfileViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
2023-12-16 12:00:38 -05:00
serializer_class = ProfileSerializer
queryset = ProfileModel.objects.all
def get_object(self):
obj = self.queryset().get(pk=self.request.user.pk)
return obj
def perform_update(self, serializer, pk=None):
profile: ProfileModel = self.get_object()
2023-12-06 09:19:41 -05:00
avatar = self.request.data.get("file", None)
if (avatar is not None):
2023-12-11 06:43:36 -05:00
if (profile.avatar_url.name != "./profiles/static/avatars/default.avif"):
2023-12-06 09:19:41 -05:00
profile.avatar_url.storage.delete(profile.avatar_url.name)
profile.avatar_url = avatar
2023-12-16 12:00:38 -05:00
profile.save()
def retrieve(self, request: HttpRequest, pk=None):
instance: ProfileModel = self.get_object()
instance.avatar_url.name = instance.avatar_url.name[instance.avatar_url.name.find("static") - 1:]
return Response(self.serializer_class(instance).data,
2023-12-16 12:02:07 -05:00
status=status.HTTP_200_OK)