0

I am working on a DRF backend API and React client. Whenever I send the data back to the server I get an error category: this field is required which is true, but I am providing that field.

I have modified the actual create() viewset function in order to add additional data to the logic:

class QuestionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows user to view and edit Question model
    """
    queryset = Question.objects.all().order_by('-updated_at')
    serializer_class = QuestionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['created_by', 'created_at', 'updated_at', 'status', 'score']

    def create(self, request, *args, **kwargs):
        serializer = QuestionSerializer(data=request.data, context={'request': request})
        if not serializer.is_valid():
            return Response(serializer.errors, status=400)
        serializer.save(created_by=request.user)
        return Response({
            'question': serializer.data
        })

I am getting that 400 status response whenever I send a message that is printed in the same backend console: <QueryDict: {'question': ['test'], 'category': ['2']}>

The serializer itself:

class QuestionSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    answers = AnswerSerializer(many=True, source='answer_set', allow_null=True, required=False)
    expert = UserSerializer(required=False)
    moderator = UserSerializer(required=False)
    created_by = UserSerializer(required=False)

        class Meta:
        model = Question
        fields = [
            'id',
            'category',
            'question',
            'status',
            'expert',
            'moderator',
            'created_by',
            'created_at',
            'updated_at',
        ]

I have tried changing category for category_id but it does not work either. My client function is something like this:

    const query = useQuery();
    const urlSufix = query.get('category') !== null ? `${query.get('category')}/` : '';
    const [{ 
        data: categoryData, 
        loading: loadingCategory, 
        error: categoryError 
    }] = useAxios(CategoryResource.urlRoot + `${urlSufix}`);

async function submitForm(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        if (!Array.isArray(categoryData)) {
            formData.append('category', categoryData.id);
        }

        const result = await submitQuestion({ data: formData });
        if (result.status == 200) {
            toast.success('question submitted');
        } else if(result.status == 400) {
            toast.error('validation error');
        } else {
            toast.error('server error');
        }
    }

So, why am I getting the error field is required despite it is being sent anyway?

Maramal
  • 3,145
  • 9
  • 46
  • 90
  • 1
    As a side note, the issue is because you have been sending a PK value for `category`, but the DRF expect it to be a `dict` since you have set `category = CategorySerializer()` – JPG Apr 24 '21 at 04:10
  • 1
    So, either you have to send the values as `dict` (personally, I wouldn't do that) or follow [this method](https://stackoverflow.com/a/52246232/8283848) – JPG Apr 24 '21 at 04:11

0 Answers0