Bird
Raised Fist0
Djangoframework~20 mins

Request parsing and response rendering in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Request Parsing and Response Rendering Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Django view when receiving a POST request with JSON data?

Consider this Django view that parses JSON data from a POST request and returns a JSON response:

from django.http import JsonResponse
import json

def my_view(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        name = data.get('name', 'Guest')
        return JsonResponse({'greeting': f'Hello, {name}!'})
    return JsonResponse({'error': 'Only POST allowed'}, status=405)

What will be the JSON response body if the POST request body is {"name": "Alice"}?

Django
from django.http import JsonResponse
import json

def my_view(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        name = data.get('name', 'Guest')
        return JsonResponse({'greeting': f'Hello, {name}!'})
    return JsonResponse({'error': 'Only POST allowed'}, status=405)
A{"greeting": "Hello, Alice!"}
B{"greeting": "Hello, Guest!"}
C{"error": "Only POST allowed"}
DSyntaxError
Attempts:
2 left
💡 Hint

Look at how the JSON body is parsed and how the 'name' key is used.

📝 Syntax
intermediate
1:30remaining
Which option correctly parses JSON data in a Django view?

Which of the following code snippets correctly parses JSON data from a Django request object?

Adata = request.json()
Bdata = request.POST.json()
Cdata = json.loads(request.body.decode('utf-8'))
Ddata = json.parse(request.body)
Attempts:
2 left
💡 Hint

Remember that request.body is a byte string and you need to decode it properly.

🔧 Debug
advanced
2:00remaining
Why does this Django view raise a TypeError when returning JsonResponse?

Examine this Django view:

from django.http import JsonResponse

def my_view(request):
    data = {'count': 5, 'items': [1, 2, 3]}
    return JsonResponse(data, safe=False)

Why does this code raise a TypeError?

Django
from django.http import JsonResponse

def my_view(request):
    data = {'count': 5, 'items': [1, 2, 3]}
    return JsonResponse(data, safe=False)
ABecause safe=False is required only when returning a list, not a dict
BBecause safe=False is used with a dict, which is not allowed
CBecause JsonResponse cannot serialize lists inside dicts
DBecause the data dict is missing a status code
Attempts:
2 left
💡 Hint

Check the meaning of the safe parameter in JsonResponse.

state_output
advanced
1:00remaining
What is the HTTP status code of this Django JsonResponse?

Given this Django view:

from django.http import JsonResponse

def error_view(request):
    return JsonResponse({'error': 'Not found'}, status=404)

What HTTP status code will the response have?

Django
from django.http import JsonResponse

def error_view(request):
    return JsonResponse({'error': 'Not found'}, status=404)
A500
B404
C200
D400
Attempts:
2 left
💡 Hint

Look at the status parameter in JsonResponse.

🧠 Conceptual
expert
2:30remaining
Which Django feature automatically parses JSON request bodies in views?

In Django, which feature or tool automatically parses JSON request bodies and provides the data as a Python dictionary without manually calling json.loads(request.body)?

AUsing Django's HttpRequest.POST attribute
BUsing Django's middleware for JSON parsing
CUsing Django's built-in JsonResponse
DUsing Django REST Framework's Request object
Attempts:
2 left
💡 Hint

Think about popular Django extensions for APIs.

Practice

(1/5)
1. What is the main purpose of JsonResponse in Django?
easy
A. To send JSON data back to the client as an HTTP response
B. To parse JSON data from the client's request body
C. To convert Python objects into HTML templates
D. To handle file uploads in a Django view

Solution

  1. Step 1: Understand JsonResponse role

    JsonResponse is a Django class that formats Python data as JSON and sends it as an HTTP response.
  2. Step 2: Differentiate from request parsing

    Parsing JSON from requests is done with json.loads() or similar, not JsonResponse.
  3. Final Answer:

    To send JSON data back to the client as an HTTP response -> Option A
  4. Quick Check:

    JsonResponse sends JSON responses [OK]
Hint: JsonResponse sends data out, not reads it in [OK]
Common Mistakes:
  • Confusing JsonResponse with JSON parsing
  • Thinking JsonResponse parses request data
  • Mixing up response rendering with template rendering
2. Which of the following is the correct way to parse JSON data from a Django request object named request?
easy
A. data = request.json()
B. data = json.dumps(request.body)
C. data = JsonResponse(request.body)
D. data = json.loads(request.body)

Solution

  1. Step 1: Identify JSON parsing method

    To convert JSON string to Python object, use json.loads().
  2. Step 2: Apply to request body

    request.body contains raw bytes, so decode if needed, then parse with json.loads().
  3. Final Answer:

    data = json.loads(request.body) -> Option D
  4. Quick Check:

    json.loads parses JSON string [OK]
Hint: Use json.loads to read JSON from request body [OK]
Common Mistakes:
  • Using json.dumps instead of json.loads
  • Calling non-existent request.json() method
  • Using JsonResponse to parse input
3. Given this Django view code, what will be the HTTP response content?
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"}
medium
A. Hello, Alice!
B. {"message": "Hello, {data['name']}!"}
C. {"message": "Hello, Alice!"}
D. SyntaxError

Solution

  1. Step 1: Parse JSON from request body

    The code uses json.loads(request.body) to get a Python dict with key 'name' and value 'Alice'.
  2. Step 2: Format message and return JsonResponse

    The message string becomes "Hello, Alice!" and is wrapped in a dict, then sent as JSON response.
  3. Final Answer:

    {"message": "Hello, Alice!"} -> Option C
  4. Quick Check:

    JsonResponse sends formatted JSON string [OK]
Hint: JsonResponse returns JSON string with keys and values [OK]
Common Mistakes:
  • Thinking JsonResponse returns plain text
  • Confusing string interpolation syntax
  • Expecting raw Python dict as response
4. What is wrong with this Django view code snippet for parsing JSON?
def my_view(request):
    data = json.loads(request.POST)
    return JsonResponse({"status": "ok"})
medium
A. request.POST is empty for GET requests only
B. request.POST is not a JSON string, so json.loads will fail
C. The function must return a string, not JsonResponse
D. JsonResponse cannot be used without importing

Solution

  1. Step 1: Understand request.POST content

    request.POST is a QueryDict, not a JSON string, so passing it to json.loads() causes an error.
  2. Step 2: Correct JSON parsing method

    To parse JSON, use json.loads(request.body) instead, since request.body contains raw JSON bytes.
  3. Final Answer:

    request.POST is not a JSON string, so json.loads will fail -> Option B
  4. Quick Check:

    json.loads needs JSON string, not QueryDict [OK]
Hint: Use request.body for JSON, not request.POST [OK]
Common Mistakes:
  • Passing request.POST to json.loads
  • Assuming JsonResponse needs string return
  • Ignoring HTTP method differences
5. You want to create a Django view that accepts JSON with a list of numbers under key values, sums them, and returns the sum as JSON. Which code correctly implements this?
hard
A. def sum_view(request): data = json.loads(request.body) total = sum(data['values']) return JsonResponse({'sum': total})
B. def sum_view(request): total = sum(request.POST.getlist('values')) return JsonResponse({'sum': total})
C. def sum_view(request): data = json.dumps(request.body) total = sum(data['values']) return JsonResponse({'sum': total})
D. def sum_view(request): total = sum(request.GET['values']) return JsonResponse({'sum': total})

Solution

  1. Step 1: Parse JSON body correctly

    Use json.loads(request.body) to get Python dict from JSON input.
  2. Step 2: Sum the list and return JSON response

    Extract the list under 'values', sum it, and return with JsonResponse.
  3. Final Answer:

    def sum_view(request): data = json.loads(request.body) total = sum(data['values']) return JsonResponse({'sum': total}) -> Option A
  4. Quick Check:

    Parse JSON body, sum list, return JsonResponse [OK]
Hint: Parse JSON body, then sum list, then JsonResponse [OK]
Common Mistakes:
  • Using json.dumps instead of json.loads
  • Trying to sum QueryDict values directly
  • Using request.GET or request.POST for JSON body