django request.post
时间: 2023-04-25 21:04:11 浏览: 53
Django中的request.post是一个字典对象,包含了所有通过POST方法提交的数据。可以通过request.post[key]来获取指定键的值。在视图函数中,可以通过判断request.method是否为POST来确定是否有POST数据提交。
相关问题
django request.post用法
Django中的request.post是一个字典对象,用于存储通过POST方法提交的数据。可以通过request.post.get()方法获取其中的值。例如:
```
def my_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
# 处理表单数据
else:
# 处理GET请求
```
在上面的例子中,如果请求方法是POST,就可以通过request.POST.get()方法获取表单数据中的username和password字段的值。如果请求方法是GET,则执行else语句中的代码。
django request.POST.get时contentType要求
在Django中,`request.POST.get`方法用于获取POST请求中的参数值。对于ContentType的要求取决于请求的数据类型。
1. Content-Type为application/x-www-form-urlencoded时,request.POST.get可以获取到参数值
如果请求的Content-Type为application/x-www-form-urlencoded,那么参数值会被编码成URL编码形式(key1=value1&key2=value2),并放在请求体中发送。此时可以通过request.POST.get方法获取参数值,例如:
```python
from django.http import HttpResponse
def my_view(request):
name = request.POST.get('name', '')
age = request.POST.get('age', '')
return HttpResponse('name: %s, age: %s' % (name, age))
```
2. Content-Type为application/json时,request.body获取请求体内容,需要手动解析获取参数值
如果请求的Content-Type为application/json,那么参数值会被以JSON格式放在请求体中发送。此时可以通过request.body获取请求体的内容,但是需要手动解析JSON数据才能获取到参数值,例如:
```python
import json
from django.http import HttpResponse
def my_view(request):
body = request.body
data = json.loads(body)
name = data.get('name', '')
age = data.get('age', '')
return HttpResponse('name: %s, age: %s' % (name, age))
```
需要注意的是,当Content-Type为application/json时,request.POST.get方法无法获取参数值。