Search code examples
reactjsdjangofetch

How to pass a JSON data from React to Django using POST request?


I have a React frontend which has a state variable that contains an array. I want to pass this state variable onClick to my Django's views.py. What I have so far is something like this:

App.js

const [dataSource, setDataSource] = useState([]); // Where the data is stored in

const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(dataSource),
};

const handleSubmit = () => {
    fetch("http://localhost:8000/insert", requestOptions);
};

<Popconfirm onConfirm={handleSubmit}>
    <Button>Submit</Button>
</Popconfirm>

views.py

def insert(request):
     if request.method == 'POST':
           json_data = request.POST.get() 
           # I'm not sure what should I be putting as a parameter for .get() method

     return render(request, 'frontend/index.html')

urls.py

...
urlpatterns = [
     ...
     path('insert/', views.insert),
     ...
]

Am I using the right approach? If it's right, what should I be passing as parameters to the get() method?

*P.s. I'm not using DRF for this approach and I'm building the app where Django and React is in one app (not separate) where the frontend is an app of Django.


Solution

  • Couple of things before the problem. First you should not use insert as your view name its against the rest conventions, for more read this doc

    Second make it fetch("http://localhost:8000/insert/", requestOptions);

    Third when you want to get the body all you need to do is

    import json
        data = json.loads(request.body)
    

    and you will get the post data as json in your hand