0

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.

3
  • use fetch API Commented Dec 9, 2022 at 6:07
  • just make it clear, is the javascript code in template(.html) or .js file? since you are using "{% url 'index' %}" Commented Dec 9, 2022 at 6:32
  • @MasZero it's in the template Commented Dec 9, 2022 at 7:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

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.