Home javascript Sending POST JSON request to the server Django

Sending POST JSON request to the server Django

Author

Date

Category

There is a JS code to send data as an HTML form.

async function request (url, form, csrftoken) {
  const response = await fetch (url, {
    method: 'POST',
    headers: { 'X-CSRFToken': csrftoken},
    body: new FormData (document.forms.namedItem (form)),
  })
  const result = await response.json ()
  return result
}

There is a Python script to handle the request.

def test_r (request):
  if request.method == 'POST' and request.user.is_authenticated:
    user = auth.get_user (request)
    pub = BasicText.objects.create (
      date_time = datetime.now (),
      text = request.POST.get ( 'text'),
      user_name = user,
    )
  return JsonResponse ({ 'id': f '{pub.id}', 'date_time': pub.date_time,})

In this form of Django server receives data from the HTML from (the text of the input) and stores it in the database. However, when you try to send data to the server as a JSON request.POST empty. I tried in this form to send data, but as I wrote request.POST.get () does not produce any results. request_json function does not work.

async function request_json (url, csrftoken) {
  const response = await fetch (url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application / json; charset = utf-8'
      'X-CSRFToken': csrftoken,
    },
    body: JSON.stringify ({
      'Text': 'test_data',
    }),
  })
  const result = await response.json ()
  return result
}

How to make so that you can send to Django POST request to the server with JSON data?
— PS —-
As a result, so I did (thanks for the answers):
JS

async function request (url, data, csrftoken) {
  const response = await fetch (url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application / x-www-form-urlencoded',
      'X-CSRFToken': csrftoken,
    },
    body: JSON.stringify (data),
  })
  const result = await response.text ()
  return result
}
async function check_username () {
  const url = '{% url "check_name_s"%}'
  const data = { 'name': document.getElementById ( 'name') value,.}
  const csrftoken = '{{csrf_token}}'
  const result = await request (url, data, csrftoken)
  console.log (result)
}

Python

from json import loads
def check_name_s (request):
  if request.method == 'POST':
    print (loads (request.body) [ 'name'])
  return HttpResponse ( 'hello')

Answer 1, Authority 100%

The bottom line is that the request.POST will Spars data sent from the content type application / x-www-form-urlencoded , and if the content type application / json , then get the data sent by the client can be from request.body.

Code View

@ csrf_exempt
def ajax (request):
  print ( "POST:", request.POST)
  print ( "BODY:", request.body)
  return JsonResponse ({ "status": "success"})

sends a query

import requests
requests.post ( "http://127.0.0.1:8000/ajax/", data = { "a": "b"})

log in

POST: & lt; QueryDict: { 'a': [ 'b']} & gt;
BODY: b'a = b '

And now json

requests.post ( "http://127.0.0.1:8000/ajax/", json = { "a": "b"})
POST: & lt; QueryDict: {} & gt;
BODY: b '{ "a": "b"}'

ie. you need to deserialize it.

import json
@csrf_exempt
def ajax (request):
   print ("POST:", request.POST)
   print ("BODY:", json.loads (request.body))
   return JsonResponse ({"status": "success"})

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions