Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data from React form to Django Rest Framework without a Model

Tags:

reactjs

django

I am trying to send some data from my React frontend to my Django REST backend.

My Django application does NOT have models.

I have a react form. When the user submit the button, the form "submits" three params:

  • firmNAme

  • timeframes

  • numberOfResults

I want to send these three parameters to my Django backend. To do so, I m assuming React is sending a "POST" request to the Django endpoint. I need these params in Django so that I can use them to do some manipulations for a ML model.

My React function

  handleSubmit(event){
    event.preventDefault()
    fetch("/myapi/getreactinfotwitter",{
      method:"POST",
      headers:{
        'Accept':'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        'data_options': {
          'partnerName': this.state.firmName,
          'timeframes': this.state.timeframes,
          'numberOfResults': this.state.numberOfResults,
        }
      })
    })

Now, I think the the Reast "POST" has to be matched with a Django "GET", so that Django gets the three params.

In DJANGO I have:

urls.py

path('getreactinfotwitter/', getreactinfotwitter, name="getreactinfotwitter")

myapi/views.py

@api_view(['GET', 'POST'])
def getreactinfotwitter(request):
    print(request)
    if request.method == 'GET':
        return Response(request.data)

HOWEVER

  • My request in the views.py is not getting anything.

  • In the web console, when I click submit I get POST http://localhost:8080/myapi/getreactinfotwitter/ 500 (Internal Server Error)

like image 333
Prova12 Avatar asked Apr 13 '26 15:04

Prova12


1 Answers

Here are the steps to configure your React front-end with Django REST backend.

Django Settings:

  1. Install django-cors-headers with the following command:
pip install django-cors-headers
  1. Add it to your project settings.py file:
INSTALLED_APPS = (
    ##...
    'corsheaders'
)
  1. Next, you need to add corsheaders.middleware.CorsMiddleware to the middleware classes in settings.py
MIDDLEWARE = [
    # corsheaders middleware
    'corsheaders.middleware.CorsMiddleware',
    ...
]
  1. You should allow the hosts in settings.py from where you want to get data. At the initial stage allow *
ALLOWED_HOSTS = [*]

React Settings:

  1. Install axios using the following command:
npm i axios
  1. Now follow the example in below for the React class.
import React from "react";
...
import Axios from "axios";
...


yourFunctionName = () => {

    Axios.post(`URL`, {
            'partnerName': this.state.firmName,
            'timeframes': this.state.timeframes,
            'numberOfResults': this.state.numberOfResults,
        },
        {
            headers: {
                "Authorization": `AUTHORIZATION_KEY`,
                "Content-Type": 'application/json'
            }
        }
    )
    .then(res => console.log(res))
    .catch(error => console.err(error))
}
like image 64
Fatema Tuz Zuhora Avatar answered Apr 16 '26 04:04

Fatema Tuz Zuhora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!