Request parsing helps your Django app understand what the user sends. Response rendering sends back the right information to the user.
Request parsing and response rendering in Django
Start learning this pattern below
Jump into concepts and practice - no test required
from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def my_view(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) # parse JSON request response_data = {'message': f"Hello, {data.get('name', 'Guest')}!"} return JsonResponse(response_data) # render JSON response else: return HttpResponse('Send a POST request with JSON data.')
Use request.body to get raw data sent by the user.
JsonResponse helps send JSON data back easily.
data = json.loads(request.body.decode('utf-8'))return JsonResponse({'key': 'value'})
return HttpResponse('Hello world', content_type='text/plain')
This Django view accepts POST requests with JSON data containing a 'name'. It responds with a JSON greeting. If the JSON is invalid, it returns an error. For other request types, it sends a simple text message.
from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def greet_user(request): if request.method == 'POST': try: data = json.loads(request.body.decode('utf-8')) name = data.get('name', 'Guest') response = {'greeting': f'Hello, {name}!'} return JsonResponse(response) except json.JSONDecodeError: return JsonResponse({'error': 'Invalid JSON'}, status=400) else: return HttpResponse('Please send a POST request with JSON data.', content_type='text/plain')
Remember to disable CSRF protection for API views or handle tokens properly.
Always check the request method before parsing data.
Use JsonResponse to automatically set the right headers for JSON.
Request parsing reads user data from the request body, often JSON.
Response rendering sends data back, like JSON or plain text.
Django provides easy tools like json.loads and JsonResponse to handle these tasks.
Practice
JsonResponse in Django?Solution
Step 1: Understand JsonResponse role
JsonResponseis a Django class that formats Python data as JSON and sends it as an HTTP response.Step 2: Differentiate from request parsing
Parsing JSON from requests is done withjson.loads()or similar, notJsonResponse.Final Answer:
To send JSON data back to the client as an HTTP response -> Option AQuick Check:
JsonResponse sends JSON responses [OK]
- Confusing JsonResponse with JSON parsing
- Thinking JsonResponse parses request data
- Mixing up response rendering with template rendering
request?Solution
Step 1: Identify JSON parsing method
To convert JSON string to Python object, usejson.loads().Step 2: Apply to request body
request.bodycontains raw bytes, so decode if needed, then parse withjson.loads().Final Answer:
data = json.loads(request.body) -> Option DQuick Check:
json.loads parses JSON string [OK]
- Using json.dumps instead of json.loads
- Calling non-existent request.json() method
- Using JsonResponse to parse input
from django.http import JsonResponse
import json
def my_view(request):
data = json.loads(request.body)
result = {"message": f"Hello, {data['name']}!"}
return JsonResponse(result)And the client sends JSON body:
{"name": "Alice"}Solution
Step 1: Parse JSON from request body
The code usesjson.loads(request.body)to get a Python dict with key 'name' and value 'Alice'.Step 2: Format message and return JsonResponse
The message string becomes "Hello, Alice!" and is wrapped in a dict, then sent as JSON response.Final Answer:
{"message": "Hello, Alice!"} -> Option CQuick Check:
JsonResponse sends formatted JSON string [OK]
- Thinking JsonResponse returns plain text
- Confusing string interpolation syntax
- Expecting raw Python dict as response
def my_view(request):
data = json.loads(request.POST)
return JsonResponse({"status": "ok"})Solution
Step 1: Understand request.POST content
request.POSTis a QueryDict, not a JSON string, so passing it tojson.loads()causes an error.Step 2: Correct JSON parsing method
To parse JSON, usejson.loads(request.body)instead, sincerequest.bodycontains raw JSON bytes.Final Answer:
request.POST is not a JSON string, so json.loads will fail -> Option BQuick Check:
json.loads needs JSON string, not QueryDict [OK]
- Passing request.POST to json.loads
- Assuming JsonResponse needs string return
- Ignoring HTTP method differences
values, sums them, and returns the sum as JSON. Which code correctly implements this?Solution
Step 1: Parse JSON body correctly
Usejson.loads(request.body)to get Python dict from JSON input.Step 2: Sum the list and return JSON response
Extract the list under 'values', sum it, and return withJsonResponse.Final Answer:
def sum_view(request): data = json.loads(request.body) total = sum(data['values']) return JsonResponse({'sum': total}) -> Option AQuick Check:
Parse JSON body, sum list, return JsonResponse [OK]
- Using json.dumps instead of json.loads
- Trying to sum QueryDict values directly
- Using request.GET or request.POST for JSON body
