如何使用Django Rest Framework更新用户信息?

时间:2017-06-21 03:52:59

标签: python angularjs django django-rest-framework

我正在尝试通过组合Django Rest Framework和Angular来实现身份验证,但我正在遭受用户信息更新。
Angular使用PUT方法将其发送到Django,Django通过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)

此时,Django接受以下请求。

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

序列化器正在实现如下。

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

我试图在这样的实现中从Angular更新用户,并返回以下响应 "{"username":["account with this username already exists."],"email":["account with this email address already exists."]}"

据认为,这是因为您没有指定要更新的记录,但有没有办法在不改变当前配置的情况下巧妙地解决它?
我需要你的帮助。

1 个答案:

答案 0 :(得分:2)

使用

class AuthInfoUpdateView(generics.UpdateAPIView):

使用http方法补丁可以partial_update你的实例。

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