0
0
Djangoframework~10 mins

Request parsing and response rendering in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Django JsonResponse class.

Django
from django.http import [1]
Drag options to blanks, or click blank then click option'
AHttpResponse
BJsonResponse
CHttpRequest
Drender
Attempts:
3 left
💡 Hint
Common Mistakes
Using HttpResponse instead of JsonResponse for JSON data.
Importing render instead of JsonResponse.
2fill in blank
medium

Complete the code to parse JSON data from a POST request in a Django view.

Django
import json

def my_view(request):
    data = json.loads(request.[1].decode('utf-8'))
    return JsonResponse({'received': data})
Drag options to blanks, or click blank then click option'
Aheaders
BGET
Cbody
DPOST
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.POST which is for form data, not raw JSON.
Trying to parse request.GET which is for URL parameters.
3fill in blank
hard

Fix the error in the code to return a JSON response with a status code 201.

Django
from django.http import JsonResponse

def create_item(request):
    response = JsonResponse({'message': 'Created'})
    response.[1] = 201
    return response
Drag options to blanks, or click blank then click option'
Astatus_code
Bstatus
Ccode
DstatusCode
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'status' or 'statusCode' which are not valid attributes.
Trying to pass status code as a parameter after creating the response.
4fill in blank
hard

Fill both blanks to parse JSON data and return a JsonResponse with a custom status code.

Django
import json
from django.http import JsonResponse

def update_view(request):
    data = json.loads(request.[1].decode('utf-8'))
    return JsonResponse({'updated': data}, status=[2])
Drag options to blanks, or click blank then click option'
Abody
BPOST
C201
D200
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.POST instead of request.body for JSON data.
Using status code 201 for update instead of 200.
5fill in blank
hard

Fill all three blanks to parse JSON from request, extract a field, and return it in JsonResponse.

Django
import json
from django.http import JsonResponse

def echo_name(request):
    data = json.loads(request.[1].decode('utf-8'))
    name = data.get('[2]', 'Guest')
    return JsonResponse({'name_echo': [3])
Drag options to blanks, or click blank then click option'
Abody
Busername
Cname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'username' instead of 'name' as the key.
Returning the string 'name' instead of the variable.