JSONDecodeError - request.body returns empty string Django

520 Views Asked by At

I am trying to access some JSON data from my views.py page but it seems i'm sending empty strings?

My JS code

document.querySelector('#compose-form').onsubmit = () => {
    
    const recipients = document.querySelector('#compose-recipients').value
    const subject = document.querySelector('#compose-subject').value
    const body = document.querySelector('#compose-body').value

    fetch('/emails', {
      method: 'POST',
      body: JSON.stringify({
        recipients: String(recipients),
        subject: String(subject),
        body: String(body)
      })
    })

    .then(response => response.json())
    .then(result => {

      load_mailbox('sent');
      console.log(result);
    });

    return false;
  };

What i was trying to replicate:

fetch('/emails', {
  method: 'POST',
  body: JSON.stringify({
      recipients: '[email protected]',
      subject: 'Meeting time',
      body: 'How about we meet tomorrow at 3pm?'
  })
})
.then(response => response.json())
.then(result => {
    // Print result
    console.log(result);
});

recipient, subject, and body are expected to be strings, given that i am grabbing mine from a form and have them in a variable i thought to convert them to strings

**Template **

<form id="compose-form" action="{% url 'compose' %}" method="POST">
            <div class="form-group">
                From: <input disabled class="form-control" value="{{ request.user.email }}">
            </div>
            <div class="form-group">
                To: <input id="compose-recipients" class="form-control">
            </div>
            <div class="form-group">
                <input class="form-control" id="compose-subject" placeholder="Subject">
            </div>
            <textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
            <input type="submit" class="btn btn-primary" id="compose-submit"/>
        </form>

URL

path("emails/", views.compose, name="compose"),

Views.py

    data_unicode = request.body.decode('utf-8') 
    data = json.loads(data_unicode)

when i debug this is what i get:

(return) body: b' '

data_unicode: ' '

0

There are 0 best solutions below