1

I have an ajax request, and in django view, i have following prints and outputs.

I have the error in this line and i cant figured it out why.

parsed_json = json.loads(request.body)

I trid to decode request body with utf8 but nothing has changed

AJAX CALL:

$("#add_user_button").click(function (event) {
    event.preventDefault();  
    $.ajax({
        type: "POST",
        url: '/user/',
        data:
            {
                'action': "addUser",
                'username': $('#id_username').val(),
                'password': $('#id_password').val(),
                'groups': $('#id_groups').val()
            }
        ,
        contentType: 'application/json; charset=utf-8',
        processData: false,
    });
}

DJANGO VIEW PRINTS:

print(request.POST.get("username"))
#print(request.encoding) #returns none
print("Request body is :")
print(request.body)
print(type(request.body))

OUTPUTS:

hello
Request body is :
b'username=hello&password=world&csrfmiddlewaretoken=&addUser=Add+User'
<class 'bytes'>

1 Answer 1

3

If you analyse your request body you'll notice it is not JSON, to send JSON you have to encode it in your ajax request from your object.

$("#add_user_button").click(function (event) {
    event.preventDefault();  
    $.ajax({
        type: "POST",
        url: '/user/',
        data:
            JSON.stringify({ // <--here
                'action': "addUser",
                'username': $('#id_username').val(),
                'password': $('#id_password').val(),
                'groups': $('#id_groups').val()
            })
        ,
        contentType: 'application/json; charset=utf-8'
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.