I have two models User and Profile which is related by One to One relation. I have registered users who can login and if profile is not created for user, then user can create one profile (using POST) and if profile is created then user can update their profile (using PATCH).
Models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='profile')
locality = models.CharField(max_length=70, null=True, blank=True)
city = models.CharField(max_length=70, null=True, blank=True)
address = models.TextField(max_length=300, null=True, blank=True)
pin = models.IntegerField(null=True, blank=True)
state = models.CharField(max_length=70, null=True, blank=True)
profile_image = models.ImageField(upload_to='user_profile_image', blank=True, null=True)
Serializer.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model= Profile
fields = ['user', 'locality','city','address','pin','state','profile_image']
Views.py
class UserProfileDataView(APIView):
renderer_classes = [UserRenderer]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
serializer = ProfileSerializer(request.user.profile, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = ProfileSerializer(data= request.data, context={'user': request.user})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED
)
def patch(self, request, format=None):
item = Profile.objects.get(user = request.user)
serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'user': request.user.profile})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({'msg':'Profile Updated Successfull'}, status = status.HTTP_200_OK)
API using Redux Toolkit
editProfile: builder.mutation({
query: (access_token, actualData ) => {
return {
url:'editprofile/',
method:'PATCH',
body:actualData,
headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'}
}
}
}),
createProfile: builder.mutation({
query: (access_token, actualData ) => {
return {
url:'createprofile/',
method:'POST',
body:actualData,
headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'}
}
}
}),
}) })
When I create profile from django admin for a user and tries to update its data, then I only get {"msg": "Profile Updated Successfull"} in network console but data is not reflected in database. and also when I try to create profile of user from Fronend using React, it gives error msg {"errors": {"user": ["This field is required."]}}