when get data from request.POST or request.body
In Django, you can retrieve data from a request using either request.POST or request.body, depending on the content type of the request and how the data is being sent. Here’s a detailed explanation of when to use each:
1. Using request.POST
字典格式的form data
- When to Use: Use
request.POSTwhen your form is submitted via a standard HTML form submission (usingapplication/x-www-form-urlencodedormultipart/form-datacontent types). - How to Access: Data is accessed as a dictionary-like object.
-
def item_update(request, pk): if request.method == 'POST': name = request.POST.get('name') description = request.POST.get('description') # Process the data as needed
2. Using
request.body - 第三方前端推送,或者把這個(gè)form字典格式的form data
-
let person = { name: "張三", age: 30, city: "北京" }; let jsonString = JSON.stringify(person); console.log(jsonString); // 輸出 '{"name":"張三","age":30,"city":"北京"}'
或者form
-
fetch('{% url "myapp1:item_update" form.instance.id %}', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }, body: JSON.stringify(this.form) })
-
- When to Use: Use
request.bodywhen your request is sending JSON data (typically with theapplication/jsoncontent type) or when you are not using a standard form submission. - How to Access: You need to parse the raw body of the request because it will be a byte string. Use
json.loads()to convert it to a Python dictionary.-
import json from django.http import JsonResponse def item_update(request, pk): if request.method == 'POST': try: data = json.loads(request.body) # Parse the JSON data name = data.get('name') description = data.get('description') # Process the data as needed return JsonResponse({'success': True}) except json.JSONDecodeError: return JsonResponse({'error': 'Invalid JSON'}, status=400)
Summary of Differences
Feature request.POSTrequest.bodyUse Case Standard form submissions JSON data or raw body content Access Method Directly as a dictionary-like object Requires parsing with json.loads()Content-Type application/x-www-form-urlencodedormultipart/form-dataapplication/jsonConclusion
- Use
request.POSTfor traditional form submissions. - Use
request.bodywhen dealing with JSON or other raw data formats. - Ensure to handle errors (like JSON decoding errors) when using
request.body.
- Use
-
- When to Use: Use
如果你是從HTML表單接收數(shù)據(jù),并且數(shù)據(jù)是通過編碼為application/x-www-form-urlencoded的,使用request.POST。
如果你是從API客戶端接收數(shù)據(jù),并且數(shù)據(jù)是以JSON或其他格式編碼的,使用request.body,然后根據(jù)實(shí)際情況解析數(shù)據(jù)

浙公網(wǎng)安備 33010602011771號(hào)