简体   繁体   中英

How to update user information using Django Rest Framework?

I am trying to implement authentication by combining Django Rest Framework and Angular, but I am suffering from user information update.
Angular sends it to Django with the PUT method, Django accepts the request with View "AuthInfoUpdateView".

class AuthInfoUpdateView(generics.GenericAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = AccountSerializer
    lookup_field = 'email'
    queryset = Account.objects.all()

    def put(self, request, *args, **kwargs):
        serializer = AccountSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

At this time, Django accepts the request as below.

request.data = {'email': 'test3@example.com', 'username': 'test3', 'profile': 'i am test3'}
request.user = test3@example.com

And the serializer is implementing as below.

from django.contrib.auth import update_session_auth_hash
from rest_framework import serializers

from .models import Account, AccountManager

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'username', 'email', 'profile', 'password')

    def create(self, validated_data):
        return Account.objects.create_user(request_data=validated_data)

    def update(self, instance, validated_data):
        insntance.username = validated_data.get('username', instance.username)
        insntance.email = validated_data.get('email', instance.email)
        insntance.profile = validated_data.get('profile', instance.profile)
        instance = super().update(instance, validated_data)
        return instance

I tried to update the user from Angular in such an implementation, and the following response is returned.
"{"username":["account with this username already exists."],"email":["account with this email address already exists."]}"

It is thought that it is because you did not specify the record to update, but is there a way to solve it smartly without changing the current configuration so much?
I need your help.

use

class AuthInfoUpdateView(generics.UpdateAPIView):

use http method patch can partial_update your instance.

method PATCH -> partial update instance 
method PUT -> update instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM