ft_transcendence/profiles/viewsets.py

44 lines
1.8 KiB
Python
Raw 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
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.order_by('-pk')
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):
instance = self.get_object()
instance.avatar_url.name = instance.avatar_url.name.replace("profiles", "", 1)
return Response(self.serializer_class(instance).data,
status=status.HTTP_200_OK)
2023-12-08 11:36:41 -05:00
def get_queryset(self):
profiles = ProfileModel.objects.all()
for profile in profiles:
profile.avatar_url.name = profile.avatar_url.name.replace("profiles", "", 1)
return profiles
2023-12-06 09:19:41 -05:00
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def perform_update(self, serializer):
query: QuerySet = ProfileModel.objects.filter(pk=self.request.user.pk)
if (not query.exists()):
return Response("profile not found", status=status.HTTP_400_BAD_REQUEST)
profile: ProfileModel = ProfileModel.objects.get(pk=self.request.user.pk)
avatar = self.request.data.get("file", None)
if (avatar is not None):
if (profile.avatar_url.name != "default.avif"):
profile.avatar_url.storage.delete(profile.avatar_url.name)
profile.avatar_url = avatar
profile.save()