Desiigner
Desiigner

Reputation: 2336

Django receiving QueryDict instead of JSON (from jQuery post)

I have a Django Rest API on back-end that stores questions and answers. I also have question sessions, it's an array of questions that has to be processed within 1 request.

The problem is, it works well when I send those requests from curl but when I do this via jquery Django receives QueryDict instead of json.

My js:

$.post('http://127.0.0.1:8000/api/sessions/create/', {
    questions: JSON.stringify(questions)
  })

When I log JSON.stringify(questions) I see it's looking like it has to be:

[{"description":"test5","type":"YESNO","to_close":5,"choices":""},{"description":"test5","type":"YESNO","to_close":5,"choices":""}]

I can even copy and paste it to curl, and it will work:

curl -X POST http://127.0.0.1:8000/api/sessions/create/ -H 'Content-Type: application/json' --data '{"questions":[{"description":"test4","type":"YESNO","to_close":5,"choices":""},{"description":"test3","type":"YESNO","to_close":5,"choices":""}]}'

But when I do via JS, Django receives it this way:

<QueryDict: {'questions': ['[{"description":"test5","type":"YESNO","to_close":5,"choices":""},{"description":"test7","type":"YESNO","to_close":5,"choices":""}]']}>

My post method looks like this:

def post(self, request, **kwargs):
    """Create a session of questions"""

    question_data = request.data.pop('questions')
    session = QuestionSession.objects.create()

    for question in question_data:
        Question.objects.create(
            description=question['description'],
            question_type=question['type'],
            answers_to_close=question['to_close'],
            question_session=session)

    serializer = QuestionSessionSerializer(data=request.data, many=True)
    serializer.is_valid()

    serializer.save()

    return Response({
        'status': 'SUCCESS',
        'message': 'A new session has been created!'
    })

What is wrong? Since I can easily do it via curl, I think the problem is in jquery request.

Upvotes: 0

Views: 828

Answers (1)

Satoe Sakuma
Satoe Sakuma

Reputation: 103

I was having this exact same issue and what has worked for me was adding , content_type="application/json" inside my post.

Upvotes: 5

Related Questions