Home > Back-end >  How to insert data and update data in One to One Relation in DRF and React Js
How to insert data and update data in One to One Relation in DRF and React Js

Time:08-14

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."]}}

CodePudding user response:

I think you missed setting the user_id field in the request payload. In the ProfileSerializer, you need to change the user field into user_id.

class ProfileSerializer(serializers.ModelSerializer):

    class Meta: 
        model= Profile 
        fields = ['user_id', 'locality','city','address','pin','state','profile_image']
        extra_kwargs = {
            'user_id': {'source': 'user'}
        }

And in the frontend, you need to set the user_id attribute in the actual_data object.

Or in the backend, you can add that field manually in the post method of the UserProfileDataView class.

class UserProfileDataView(APIView):
    ...

    def post(self, request, format=None):
        input_data = request.data
        input_data['user_id'] = request.user.id
        serializer = ProfileSerializer(data= input_data, context={'user': request.user})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED 
    )
  • Related