Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - How to send a query from the frontend (React) to Django with Rest Framework

i want to receive a particular input from the frontend react textarea to perform a certain function in django backend. Anybody to help. i want to send a input's value from the textarea input field to my backend

Here is my React Frontend Code

import React, { Component } from 'react';
import axios from 'axios';

class QueryBuilder extends Component{
render() {
    return (
        <div>
            <form>
                <textarea cols="100" rows="20" name="text" />
                <br /><br />
                <button>Execute Query</button>
            </form>

        </div>
        )
    }
}

export default QueryBuilder; 

 

Here is the views.py code

from django import db
from django.shortcuts import render, HttpResponse
from rest_framework import generics
from .models import Test
from .serializers import TestSerializer
from pymongo import MongoClient
from ast import literal_eval
from rest_framework import viewsets, permissions
# from .models import Test
# from .serializers import TestSerializer
    
#Test Viewset
class TestViewset(viewsets.ModelViewSet):
    client = MongoClient()
    db = client.test
    # collect = db['state_entry'].find({})
    queryset = db['queryTest_test'].find({})
    permission_classes = [
        permissions.AllowAny
    ]
    
    serializer_class = TestSerializer

Serializer.py

from rest_framework import serializers
from queryTest.models import Test
# Test Serializers

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test
        fields = '__all__'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update your react component code to this, i see you have imported axios but havent't used it to make api call, You should definitely checkout axios official documentation, very useful package

import React, { Component } from "react";
import axios from "axios";

class App extends Component {
    constructor() {
        this.state({
            textAreaValue: "",
        });
    }
    api_call = (data) =>
        axios
            .post(`http://127.0.0.1:8000/your-api-path`, {
                value_to_send: data,
            })
            .then(function (response) {
                console.log(response);
                this.setState({textAreaValue:''});
            })
            .catch(function (error) {
                console.log(error);
            });
    render() {
        return (
            <div>
                <textarea
                    onChange={(e) => this.setState({textAreaValue: e.target.value})}
                    value={this.state.textAreaValue}
                />
                <button onClick={() => this.api_call(this.state.textAreaValue)}>Click it</button>
            </div>
        );
    }
}

export default App;

Update your viewset to this i.e. use self.request.data received in api request

from django import db
from django.shortcuts import render, HttpResponse
from rest_framework import generics
from .models import Test
from .serializers import TestSerializer
from pymongo import MongoClient
from ast import literal_eval
from rest_framework import viewsets, permissions
# from .models import Test
# from .serializers import TestSerializer
    
#Test Viewset
class TestViewset(viewsets.ModelViewSet):
    request_data = request.data
    print(request_data)
    client = MongoClient()
    db = client.test
    # collect = db['state_entry'].find({})
    queryset = db['queryTest_test'].find({})
    permission_classes = [
        permissions.AllowAny
    ]
    
    serializer_class = TestSerializer

Have a look at django request/response docs here

Checkout this answer here for a similar requirement in backend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...