Sajad
Sajad

Reputation: 61

Django user update is not working

I have this user serializer:

class SimpleUser(models.Model):
    class meta:
        abstract = True

    email = models.EmailField(_('email address'), blank=False)
    password = models.CharField(_('password'), max_length=128)
    first_name = models.EmailField(_('first name'), blank=True)

class UserSerializer(ModelSerializer):
    class Meta:
        model = SimpleUser

And this is my view:

class UserView(APIView):
    def patch(self, request, user_id):
        firstname = request.data.get('first_name', '')
        email = request.data.get('email', '')
        password = request.data.get('password', '')

        user = User.objects.get(id=user_id)
        serializer = UserSerializer(instance=user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(status=status.HTTP_200_OK)
        return Response(status=status.HTTP_400_BAD_REQUEST)

I send this json request, but only the password and email are updated and first_name not updated.

{
"password":"6524266",
"email":"[email protected]",
"first name":"dsfxvxc"
}

I get the status 200 OK and can get the saved object in serializer.save()

What is wrong with my code?

Upvotes: 0

Views: 134

Answers (1)

Renjith Thankachan
Renjith Thankachan

Reputation: 4346

You set firstname as emailfield

first_name = models.EmailField(_('first name'), blank=True)

Changes this to CharField or related fields, something like this,

first_name = models.CharField(max_length=30)

Upvotes: 1

Related Questions