3

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)

5
  • 1
    quick google search led me to this, may be this will help you valentinog.com/blog/drf Commented Sep 16, 2019 at 18:06
  • 1
    I think the the Reast "POST" has to be matched with a Django "GET" this is wrong. If you send data by react with post method then, use post also inside the django view. I would recommend you to use the Postman software to check first your django-rest api works and then work with the React Commented Sep 17, 2019 at 9:59
  • Can you elaborate more on why I should use POST on Django if it is receiving data from React? Commented Sep 17, 2019 at 10:09
  • 1
    post, get, put, patch, delete etc are http methods by which client requests server to do something. At this API era, the same API url is used for different purposes (to get some data from server, to save some data to the database by the backend code, to edit something etc.). That's why the server has to check the method of request to response client. If client needs something from server then client send a get request to the server via an url. The server then check the method of request (here, get) and responses something depending on the method. Commented Sep 17, 2019 at 11:31
  • Have your problem solved ? Commented Sep 18, 2019 at 1:06

3 Answers 3

7

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))
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but how should I fetch the request in views.py? My React is POSTING, how do I catch in the back what React is posting?
Hey, If this answer helps you then plz accept the answer.
I do not get your point to fetch the request in views.py. Do you mean something like that - You want to see and catch the data that has been requested from React app??
No, I need to get from the React form the "params" (partnerName, timeframes, numberOfResults") to that I can modify them in python.
6

Fatima's answer is excellent enough. I am adding here some extra thing that you wanted to know in comment.

Basically you don't need to catch the data manually and save it into database. Django gives us extreme flexibility. If your model, serializer and view are like below then any axios request will be handled by django itself (i.e, django catches the data and saves it into database), you don't need to write code for manually save it into database.

Model

class Partner(models.Model):
    partnerName =  models.CharField(max_length=100)
    timeFrames = models.IntegerField()
    numberOfResults = models.IntegerField()

Serializer

class PartnerSerializer(serializer.ModelSerializer):
    class Meta:
        model=Partner
        fields = '__all__'

Views

class PartnerView():
    queryset = Partner.object.all()
    serializer_class = PartnerSerializer

If you still want to catch the data inside the view and modify in your way then just add built in function create() (builtin function of ModelViewSet) in your view class. If you want to modify the data inside serializer instead of view then add the builtin create() function (built in function of ModelSerializer) in your serializer.

The mentioned built in function (and also many more built in function) can be found in this website http://www.cdrf.co/

Exact url of create() function of view is this and

Exact url of create() function of serializer is this

See the code below of customization.

Customized Views

class PartnerView():
    queryset = Partner.object.all()
    serializer_class = PartnerSerializer

    def create(self, request, *args, **kwargs):        
        serializer = self.get_serializer(data=request.data)        
        serializer.is_valid(raise_exception=True)

        # Here all incoming data we kept in serializer variable.
        # Change the data in your way and then pass it inside perform_create()

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(
           data={
               "status": 201,
               "message": "Product Successfully Created",                
               "data": serializer.data,                
               },
               status=status.HTTP_201_CREATED,
               headers=headers
           )

If you want to modify the data inside the serializer then use the below code.

Customized Serializer

    class PartnerSerializer(serializer.ModelSerializer):

        class Meta:
            model = Partner
            fields = '__all__'

        def create(self, validated_data):
            my_incoming_data = validated_data

            # If you want to pop any field from the incoming data then you can like below.
            # popped_data = validated_data.pop('timeFrames')

            inserted_data = Partner.objects.create(**validated_data)

            return Response(inserted_data)

2 Comments

My application does not contain any model. How can I implement your code?
Then you should manually save it into database from the views. Here it is PartnerView. Anyway, did you solve it ? @Prova12
1

if you are trying to send data with react and fetch to an APIView in Django, the only thing you need to do is to remove the Content-Type header from fetch headers, so the DRF would set it, and you can access files and data from request.data.

DRF APIView:

class ImportProductsAPI(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated, IsAdmin)

    def put(self, request):
        # you can pass other data as well as files too.
        site_id = request.data["site_id"]
        # and there is the file you want
        file = request.data["excel"]
        return JsonReponse()

Fetch (in react project)

let formData = new FormData();
formData.append("excel", file);
formData.append("site_id", site_id);

fetch(
    "api/for/upload", 
    {    
      method: "PUT",
      headers: {
        Accept: "application/json",
        Authorization: "token thisisthetokenforthisuser",
        // consider that there is no Content-Type being setted.
        },
      body: formData,
    })
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
      });

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.