'Can't retrieve data from POST in django view
I have issue with retrieving data from POST in my django view. I send React form values with axios to my django backend. I believe data gets put into POST but somehow it seems that there isn't any data in POST and i can't access it in my django view. What could be issue here? (I can also see in my console that values are successfully submitted)
Source code:
Django views.py:
@csrf_exempt
def send(request):
if request.method == "POST":
data = request.body('name')
send_mail('Test 1', data, '[email protected]', ['[email protected]',], fail_silently=False)
return redirect('/api/')
React form handling:
handleFormSubmit = (event) => {
const name = event.target.elements.name.value;
const email = event.target.elements.email.value;
event.preventDefault();
axios.post('http://127.0.0.1:8000/api/send', {
name: name,
email: email
})
.then(res => console.log(res))
.catch(error => console.err(error));
};
New error:
File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\austi\PycharmProjects\Fitex5\backend\src\training\api\views.py", line 78, in send
data = request.body('name')
TypeError: 'bytes' object is not callable
Solution 1:[1]
This is because you're sending JSON and not FormData, the POST field is for forms. You want request.body.
Here's duplicate question: https://stackoverflow.com/a/3020756/490790
Further Update
You're trying to call a string (or bytes in this case) as a function. request.body
is not a function. If you want to get a field you'll have to parse it as JSON and then access it like a dictionary.
data = json.loads(request.body)
name = data['name']
Solution 2:[2]
parameters send in axios post request can be retrieved from request.body. Parameters = json.loads(request.body)
Now you can retrieve your parameters from this dictionary.
Solution 3:[3]
You can also directly access by:
email = request.data['email']
name = request.data['name']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | arti gupta |
Solution 3 | Abhishek Patel |