Как вставить данные и обновить данные в связи "один к одному" в DRF и React Js
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 с использованием 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'}
}
}
}),
}) })
Когда я создаю профиль из django admin для пользователя и пытаюсь обновить его данные, то получаю только {"msg": "Profile Updated Successfull"} в сетевой консоли, но данные не отражаются в базе данных. а также когда я пытаюсь создать профиль пользователя из Fronend с помощью React, он выдает ошибку {"errors": {"user": ["This field is required."]}}
Я думаю, что вы пропустили установку поля user_id
в полезной нагрузке запроса. В ProfileSerializer
необходимо изменить поле user
на 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'}
}
А во фронтенде нужно установить атрибут user_id
в объекте actual_data
.
Или в бэкенде вы можете добавить это поле вручную в методе post
класса UserProfileDataView
.
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
)