Django Rest Framework自定义用户模型PUT请求

时间:2016-06-24 22:33:52

标签: django django-rest-framework put

我在发送PUT我的自定义用户模型请求时遇到问题

在向/api/provider/1/发送PUT请求时1pk,并将数据phone_number = 1234567890发送给{"email": ["This field is required."] }

如果我发送emailphone_number,我会收到{"email": ["Provider with this email already exists."]}

模型

class ProviderManager(BaseUserManager):

    def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
        '''Creates and saves a User with the given email and password'''
        now = timezone.now()

        if not email:
            raise ValueError('Email can\'t be empty')
        email = self.normalize_email(email)
        user = self.model(email=email, is_active=True, is_superuser=is_superuser,
                          is_staff=is_staff, last_login=now, date_joined=now,
                          **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, phone_number, **extra_fields):
        extra_fields['phone_number'] = phone_number
        return self._create_user(email, password, False, False, **extra_fields)

    def create_user(self, email, password, phone_number, **extra_fields):
        extra_fields['phone_number'] = phone_number
        return self._create_user(email, password, True, True, **extra_fields)


class Provider(AbstractBaseUser):

    name = models.CharField(max_length=256, default='')
    email = models.EmailField(max_length=256, unique=True, db_index=True)
    phone_number = models.CharField(max_length=32, unique=True)
    language = models.CharField(max_length=8, default='')
    currency = models.CharField(max_length=8, default='')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['phone_number',]

    objects = ProviderManager()

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def email_user(self, subject, message, from_email=None, **kwargs):
        send_mail(subject, message, from_email, [self.email])

串行

class ProviderSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('id', 'name', 'email', 'phone_number', 'language', 'currency',)

查看

@api_view(['GET', 'PUT', 'DELETE'])
def provider_detail(request, provider_id):
    '''Read, update or delete a provider'''
    try:
        provider = User.objects.get(pk=provider_id)
    except User.DoesNotExist:
        return Response(status=HTTP_404_NOT_FOUND)

    print('GOT PROVIDER ' + provider.email)

    if request.method == 'GET':
        serializer = ProviderSerializer(provider)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ProviderSerializer(provider, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        provider.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

2 个答案:

答案 0 :(得分:0)

在进行PUT时,您需要提交模型的所有字段,只有PATCH允许您通过传递一个字段来更新

答案 1 :(得分:-1)

您可以将partial参数传递给序列化程序,以表明它是部分更新。

来自doc:
http://www.django-rest-framework.org/api-guide/serializers/#partial-updates