Cannot send javascript post data to django view

Question:

I have a function in javascript in which I am trying to a very simple key value pair of data through a post request into the same view in which the webpage is rendered from. I have a form in the same template/webpage HTML that is able to send post data to the view just fine, however the javascript is unable to do so and I am left with null data in the view.

Javascript:
`

 postAccount();
    async function postAccount() {
        accountPromise = getAccount().then(accounts => {
            return accounts[0];
        }) //This function call to retrieve the account will be put here until I can figure out a way to
        //pull the address with the user pressing login ONLY IF the the user has already connected theyre metamask.
        account = await accountPromise;
        var data = new FormData();
        data.append("address", account.toString());
        console.log("address=" + account.toString());
        let post = new XMLHttpRequest();
        post.open("POST", "{% url 'index' %}", true);
        post.setRequestHeader('Content-Type', 'application/json');
        post.send(data);
    }

Django view:

@csrf_exempt
def index(request):
    context = {}
    usernameInput = None;
    address = None;
    if (request.method == 'POST'):
        usernameInput = request.POST.get("username_input")
        address = request.POST.get("address")
        print(usernameInput, address)
    if (usernameInput != None and address != None):
        user = generalUser(address = str(address), username = usernameInput, lastLogin = timezone.now())
        user.save()
    # else: raise Exception("username or address is null!")
    return render(request, "chatswap/index.html", context)

`

I have tried changing the way data is sent in post.send() in pretty much everyway possible from JSON.stringify("address": account) to just "address=" + account.toString() but nothing seems to change it. The username input retrieved from the form post request works just fine, but the address is always null.

Asked By: PBRParker

||

Answers:

Since you are using application/json as content-type, Django does not parse the data into request.POST. Try printing request.body to see the data, and then use it.

Answered By: Mas Zero

So I’ve figured it out thank you for the help! For anyone who comes across this, I ended up using the fetch API to send the POST request to the view.

Then, I followed Mas Zero‘s instruction (accepted answer) and used request.body to access the data rather than request.POST.get().

After that, I parsed JSON data into a python dictionary with json.loads(request.body).

Answered By: PBRParker
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.