Which code snippet correctly parses the request and returns the response?
hard📝 component behavior Q8 of 15
Django - REST Framework Basics
You want to create a Django view that accepts JSON data with keys username and password, validates them, and returns a JSON response with status key. Which code snippet correctly parses the request and returns the response?
Adef login_view(request):
data = request.POST
if data.get('username') and data.get('password'):
return JsonResponse({'status': 'ok'})
return JsonResponse({'status': 'error'})
Bdef login_view(request):
data = json.loads(request.body)
if 'username' in data and 'password' in data:
return JsonResponse({'status': 'ok'})
return JsonResponse({'status': 'error'})
Cdef login_view(request):
data = json.loads(request.GET)
if 'username' in data and 'password' in data:
return JsonResponse({'status': 'ok'})
return JsonResponse({'status': 'error'})
Ddef login_view(request):
data = request.body
if 'username' in data and 'password' in data:
return JsonResponse({'status': 'ok'})
return JsonResponse({'status': 'error'})
Step-by-Step Solution
Solution:
Step 1: Parse JSON from request body
Use json.loads(request.body) to get a dictionary from JSON payload.
Step 2: Check keys and return JsonResponse
Check if keys exist in parsed dict, then return appropriate JsonResponse.
Final Answer:
Parse JSON from request.body and check keys correctly -> Option B
Quick Check:
Parse JSON with json.loads(request.body) for POST JSON [OK]
Quick Trick:Parse JSON with json.loads(request.body) for POST JSON [OK]
Common Mistakes:
MISTAKES
Using request.POST for JSON data
Trying to parse request.GET as JSON
Not parsing request.body before checking keys
Master "REST Framework Basics" in Django
9 interactive learning modes - each teaches the same concept differently