'Cannot update a Django user profile
I have a react app interacting with django to create and update user profiles. I am encountering this error message when I try to update a user profile, specifically the first name and last name properties I get a response that indicates that my user profile has not been updated
{"username":"***","email":"[email protected]","password":"****","first_name":"","last_name":""}
This is what I have in my urls.py:
path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'),
UpdateProfileView:
class UpdateProfileView(generics.UpdateAPIView):
queryset = User.objects.all()
serializer_class = UpdateUserSerializer
def profile(request):
if request.method == 'PUT':
try:
user = User.objects.get(id=request.user.id)
serializer_user = UpdateUserSerializer(user, many=True)
if serializer_user.is_valid():
serializer_user.save()
return Response(serializer_user)
except User.DoesNotExist:
return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST)
UpdateUserSerializer:
class UpdateUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = User
fields = ['username', 'email', 'password', 'first_name', 'last_name']
extra_kwargs = {'username': {'required': False},
'email': {'required': False},
'password': {'required': False},
'first_name': {'required': False},
'last_name': {'required': False}}
def validate_email(self, value):
user = self.context['request'].user
if User.objects.exclude(pk=user.pk).filter(email=value).exists():
raise serializers.ValidationError({"email": "This email is already in use."})
return value
def validate_username(self, value):
user = self.context['request'].user
if User.objects.exclude(pk=user.pk).filter(username=value).exists():
raise serializers.ValidationError({"username": "This username is already in use."})
return value
def update(self, instance, validated_data):
user = self.context['request'].user
if user.pk != instance.pk:
raise serializers.ValidationError({"authorize": "You don't have permission for this user."})
instance.first_name = validated_data['first_name']
instance.last_name = validated_data['last_name']
instance.email = validated_data['email']
instance.username = validated_data['username']
instance.save()
return instance
Any ideas where I am going wrong? To summarize one more time; I would like to enable a user to successfully update the first name and last name properties associated with a particular user
Solution 1:[1]
Edit urls.py like this
path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), name='update_profile'),
I hope this will work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aanand S |
