While Updating the User Profile, I want to keep the previous image in Database when API client do not sends any image.
Profile Data before update...
{
"first_name": "Minhajul",
"last_name": "Islam",
"gender": "Male",
"profile_pic": "/media/ProfilePic/minhaj/IMG_5441_zjuUKoe.JPG",
"bio": "bio"
}
Profile Data after update...
{
"first_name": "Minhajul Islam",
"last_name": "Sifat",
"gender": "Male",
"profile_pic": null,
"bio": "new bio"
}
Here my existing image has replaced with null when API client do not sends any image while updating.
This is screenshot of API Client's data
This is my views.py
from.serializers import UpdateSerializer
class Test(generics.UpdateAPIView, generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UpdateSerializer
lookup_field = 'username'
def list(self, request, *args, **kwargs):
username = self.kwargs.get('username')
if username != str(self.request.user):
return Response({"Invalid Request"}, status=status.HTTP_401_UNAUTHORIZED)
queryset = self.get_queryset().filter(username=self.request.user)
serializer = UpdateSerializer(queryset, many=True)
return Response(serializer.data[0], status=200)
def patch(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
This is my serializer.py
class UpdateSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'first_name',
'last_name',
'gender',
'profile_pic',
'bio',
]
What I have to do If I want to keep the existing picture when API client sends no Image?
Because you're calling update and not partial_update from the patch method. There really is no need to override the method in this case as it does exactly what you want and you're not adding anything to it. Check out how it is implemented here