Bird
0
0

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:
  1. Step 1: Parse JSON from request body

    Use json.loads(request.body) to get a dictionary from JSON payload.
  2. Step 2: Check keys and return JsonResponse

    Check if keys exist in parsed dict, then return appropriate JsonResponse.
  3. Final Answer:

    Parse JSON from request.body and check keys correctly -> Option B
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes