Задать вопрос
@ekzotika

Key Error в Post запросе Django Rest Framework?

Я хочу отправить некоторые данные, и я получаю эту ошибку KeyError at /ctm/customeroffice/ 'code'.

Мой код:

models.py

class CustomerOffice(models.Model):
        customer = models.ForeignKey(
            Customer,
            related_name='office',
            on_delete=models.SET_NULL,
            null=True
        )
        profile = models.ManyToManyField(
            CustomerProfile
        )
        trade_marks = models.ManyToManyField(
            TradeMark
        )
        specialization = models.ManyToManyField(
            OfficeSpecialization,
        )
        distributor = models.ForeignKey(
            Distributor,
            on_delete=models.SET_NULL,
            null=True
        )
        address = models.ForeignKey(
            Address,
            on_delete=models.SET_NULL,
            null=True
        )
        worker = models.ManyToManyField(
            'CRMUser',
            related_name='office'
        )
        tel = models.ManyToManyField(
            'Phone'
        )
        email = models.CharField(
            max_length=255,
            blank=True
        )
        site = models.CharField(
            max_length=255,
            blank=True
        )
        head_office = models.BooleanField(
            default=False
        )
        state = models.ForeignKey(
            State,
            related_name='representatives',
            on_delete=models.SET_NULL,
            null=True
        )
    

    class CustomerProfile(models.Model):
        name = models.CharField(
            max_length=255
        )
        code = models.CharField(
            max_length=255
        )


serializers.py

class CustomerOfficeSerializer(ModelSerializer):
    
        state = StateSerializer()
        customer = CustomerSerializer()
        address = AddressSerializer()
        distributor = DistributorSerializer()
        profile = CustomerProfileSerializer(many=True)
    
        class Meta:
            model = CustomerOffice
            fields = ('id', 'address', 'customer', 'profile', 'head_office', 'distributor', 'email', 'site', 'state', 'active')
    
        def create(self, validated_data):
            state_data = validated_data.pop('state')
            customer_data = validated_data.pop('customer')
            address_data = validated_data.pop('address')
            distributor_data = validated_data.pop('distributor')
            profile_data = validated_data.pop('profile')
            state_data = dict(state_data)
            customer_data = dict(customer_data)
            address_data = dict(address_data)
            distributor_data = dict(distributor_data)
            profile_data = dict(profile_data)
            state = State.objects.filter(name=state_data['name'], abbr=state_data['abbr'],
                                         name_en=state_data['name_en']).first()
            customer = Customer.objects.filter(sap=customer_data['sap'], sap_be=customer_data['sap_be'],
                                               name=customer_data['name'], name_en=customer_data['name_en']).first()
            address = Address.objects.filter(sub_locality=address_data['sub_locality'], postal_code=address_data['postal_code'],
                                             street_address=address_data['street_address'], house=address_data['house'],
                                             note=address_data['note'], raw_data=address_data['raw_data']).first()
            distributor = Distributor.objects.filter(name=distributor_data['name'], commercial_name=distributor_data['commercial_name']).first()
            profile = CustomerProfile.objects.filter(name=profile_data['name'], code=profile_data['code']).first()
            customer_office = CustomerOffice.objects.create(**validated_data, state=state, customer=customer,
                                                            address=address, distributor=distributor, profile=profile)
            return customer_office
    
    
    
    class CustomerProfileSerializer(ModelSerializer):
    
        class Meta:
            model = CustomerProfile
            fields = '__all__'


views.py

class CustomerOfficeAPIListView(APIView, VueTablesParams):
    
        def get(self, request, format=None):
            items = CustomerOffice.objects.order_by('pk')
            paginator = PageNumberPagination()
    
            state = request.GET.get('state', None)
            if state:
                items = items.filter(state__pk=state)
    
            super().get(
               request, items, paginator, format=None
            )
    
            result_page = paginator.paginate_queryset(items, request)
            serializer = CustomerOfficeSerializer(result_page, many=True)
            return paginator.get_paginated_response(serializer.data)
    
    
        def post(self, request, format=None):
            serializer = CustomerOfficeSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=201)
            return Response(serializer.errors, status=400)


Проблема в том, что когда я хочу отправить такие данные, как:

"{"address":{"id":34965,"sub_locality":"Murmansk","postal_code":123456,"street_address":"qwerty","house":"qwerty","note":"qwerty","raw_data":"qwerty","parsed":false,"locality":{"id":23379,"name":"Lida","name_en":"Tver","population":39378059,"area":"","region":18156}},"customer":{"id":4209,"sap":"137657","sap_be":"BE/137657","name":"ООО \"Palm\"","name_en":"OOO \"Palma\""},"distributor":{"id":3269,"name":"ТРАКСЕРВИС","commercial_name":"OMEGA"},"email":"eliz.moon5@gmail.com","site":"eliz.moon5@gmail.com","state":{"id":323,"name":"Северо-Западный федеральный округ","abbr":"СЗФО","name_en":"Northwestern Federal District","country":47},"profile":[{"id":211,"name":"Запасные части для специальной техники","code":"HD"}]}"


Я получаю эту ошибку KeyError at / ctm / customeroffice / 'code'
Мне нужна помощь. Не знаю, что делать с этим
  • Вопрос задан
  • 386 просмотров
Подписаться 1 Простой Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы