django - 无法在 django 视图中从 POST 检索数据
问题描述
我在 django 视图中从 POST 检索数据时遇到问题。我将带有 axios 的 React 表单值发送到我的 django 后端。我相信数据被放入 POST 但不知何故似乎 POST 中没有任何数据,我无法在我的 django 视图中访问它。这里可能有什么问题?(我还可以在控制台中看到值已成功提交)
源代码:
djangoviews.py:
@csrf_exempt
def send(request):
if request.method == "POST":
data = request.body('name')
send_mail('Test 1', data, 'austin.milk1@gmail.com', ['lowoko9513@gomail4.com',], fail_silently=False)
return redirect('/api/')
反应表单处理:
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));
};
新错误:
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
解决方案
这是因为您发送的是 JSON 而不是 FormData,POST 字段用于表单。你想要 request.body。
这是重复的问题:https ://stackoverflow.com/a/3020756/490790
进一步更新
您正在尝试将字符串(或本例中的字节)调用为函数。request.body
不是函数。如果你想得到一个字段,你必须将它解析为 JSON,然后像字典一样访问它。
data = json.loads(request.body)
name = data['name']
推荐阅读
- r - R中的替换函数
- postgresql - 仅当表中的行数大于 0 时,才将 PostgreSQL 表导出为带有标题的 CSV
- vba - 如果语句 - msgbox
- javascript - Observable toPromise() 获取通过 next() 发送的所有数据
- dart - 在本地获取和存储 json
- go - 为什么 imagemagick 中的 PNG 图像 readimage 和 writeimage 需要很多时间?
- java - Spring Data CouchbaseTemplate 和 setWriteResultChecking
- dataframe - 如何更改熊猫中的索引名称?
- cuda - CUDA 驱动程序 API - 最低驱动程序版本?
- git - 如何禁用 Git 自动检测电子邮件地址?