Django APIView中必填字段的错误

时间:2019-03-25 06:41:22

标签: django django-rest-framework

我正在尝试更新一名员工。我也可以更新。但是,当我不在body中发送数据时,问题就出现了,正在更新。它给出了Required Field的错误。

此错误是一种错误-我没有在excempt中发送json body

serializer2 {'excempt': [ErrorDetail(string='This field is required.', code='required')]}

即使我尝试放入required=False,它也能正常工作,但我不了解我们是否要传递该EmployeeProfileSerializer(userprofile, data=request.data)的实例。示例userprofile,但是为什么它仍然显示错误。以及我该如何解决。我认为这不是解决方法required=False

当我不在正文中发送数据时,应使用以前的数据,但这没有发生,而是出现错误required field

APIView

class EmployeeUpdateApiV2(APIView):

    def post(self, request, *args, **kwrgs):

        try:
            accesstoken=AccessToken.objects.get(
                        token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
                    )
        except ObjectDoesNotExist:
            return Response (
                {
                    "status" : False,
                    "error" : "Wrong Access Token",
                    "error_message":"You have provided wrong access token.",
                }
            )

        user_id = request.data['user_id'] 
        user = get_object_or_404(User, id=user_id)
        print(user)
        userprofile = get_object_or_404(UserProfile, user=user_id)
        print(userprofile)
        serializer1 = EmployeeRegisterSerializer(user, data=request.data)
        serializer2 = EmployeeProfileSerializer(userprofile, data=request.data)

        if serializer1.is_valid() and serializer2.is_valid():
            serializer1.save()
            serializer2.save()
            print('Inside Valid')
            return Response (
                    {
                        "status" : True,
                        "message":"Employee Updated Successfully.",
                        "api_name" : "EmployeeUpdateApiV2",
                        "result": serializer1.data,
                        "result1": serializer2.data,

                    }
                )
        print('Out Valid')
        print('serializer1 ', serializer1.errors)
        print('serializer2', serializer2.errors)
        return Response(status=status.HTTP_404_NOT_FOUND)

Serializers.py

class EmployeeProfileSerializer(serializers.ModelSerializer):
    employee_id = serializers.CharField(source='user_employee_id')
    payroll_id = serializers.CharField(source='user_payroll_id')
    hire_date = serializers.CharField(source='user_hire_date')
    pay_rate = serializers.CharField(source='user_pay_rate')
    salaried = serializers.CharField(source='user_salaried')
    excempt = serializers.CharField(source='user_excempt')
    groups = serializers.CharField(source='user_groups_id', required=False)
    state = serializers.CharField(source='user_state')
    city = serializers.CharField(source='user_city')
    zipcode = serializers.CharField(source='user_zipcode')
    status = serializers.CharField(source='user_status')
    phone = serializers.CharField(source='user_phone')
    class Meta:
        model = UserProfile
        fields = [  
                    'employee_id',
                    'phone', 
                    'payroll_id',
                    'hire_date',
                    'pay_rate',
                    'salaried',
                    'excempt',
                    'groups',
                    'state',
                    'city',
                    'zipcode', 
                    'status',
                ]

class EmployeeRegisterSerializer(serializers.ModelSerializer):   
    class Meta:
        model = User
        fields = ['first_name','last_name', 'email',]

用户个人资料模型

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_company = models.ForeignKey(Company, on_delete=models.CASCADE)
    user_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE)
    user_dob = models.DateField(null=True, blank=True)
    user_phone = models.CharField(max_length=30, blank=True, null=True)
    user_image = models.ImageField(upload_to='user_profiles/', default='default_user.png',blank=True, null=True)
    user_created = models.DateTimeField(auto_now_add=True)
    user_is_deleted = models.BooleanField(default=False)
    user_deleted_at = models.DateTimeField(blank=True, null=True)
    user_groups = models.ManyToManyField(Groups,related_name='user_groups')
    MALE = 'Male'
    FEMALE = 'Female'
    GENDER_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female'),
    )
    user_gender = models.CharField(
        max_length=8,
        choices=GENDER_CHOICES,
    )

    ACTIVE = 'Active'
    INACTIVE = 'Inactive'
    PENDING = 'Pending'
    USER_ACTIVE_CHOICES = (
        (ACTIVE, 'Active'),
        (INACTIVE, 'Inactive'),
        (PENDING, 'Pending'),
    )
    user_status = models.CharField(
        max_length=8,
        choices=USER_ACTIVE_CHOICES,
        default=ACTIVE,
    )

1 个答案:

答案 0 :(得分:0)

请在“模型序列化器”字段部分中添加user

class EmployeeProfileSerializer(serializers.ModelSerializer):
        employee_id = serializers.CharField(source='user_employee_id')
        payroll_id = serializers.CharField(source='user_payroll_id')
        hire_date = serializers.CharField(source='user_hire_date')
        pay_rate = serializers.CharField(source='user_pay_rate')
        salaried = serializers.CharField(source='user_salaried')
        excempt = serializers.CharField(source='user_excempt')
        groups = serializers.CharField(source='user_groups_id', required=False)
        state = serializers.CharField(source='user_state')
        city = serializers.CharField(source='user_city')
        zipcode = serializers.CharField(source='user_zipcode')
        status = serializers.CharField(source='user_status')
        phone = serializers.CharField(source='user_phone')
        class Meta:
            model = UserProfile
            fields = [  
                        'employee_id',
                        'phone', 
                        'payroll_id',
                        'hire_date',
                        'pay_rate',
                        'salaried',
                        'excempt',
                        'groups',
                        'state',
                        'city',
                        'zipcode', 
                        'status',
                        'user',

                    ]