0

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.

1
  • 1
    post method suppose to end in /. And check the request.body to receive raw data and then you can use json.loads to convert to dictionary. Commented Nov 6, 2021 at 4:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.