0
0
Djangoframework~15 mins

Returning JSON with JsonResponse in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Returning JSON with JsonResponse
📖 Scenario: You are building a simple Django web app that needs to send data as JSON to the browser. This is common when making APIs or dynamic web pages that use JavaScript to fetch data.
🎯 Goal: Create a Django view that returns a JSON response using JsonResponse with a dictionary of user information.
📋 What You'll Learn
Create a dictionary called user_data with keys name, age, and city and their exact values.
Create a variable called status_code and set it to 200.
Write a Django view function called user_info that returns a JsonResponse with user_data and status=status_code.
Add the necessary import for JsonResponse from django.http.
💡 Why This Matters
🌍 Real World
APIs often send data as JSON to web browsers or other apps. Django's JsonResponse makes it easy to send JSON data from your server.
💼 Career
Knowing how to return JSON responses is essential for backend web developers building APIs or dynamic web applications.
Progress0 / 4 steps
1
Create the user data dictionary
Create a dictionary called user_data with these exact entries: 'name': 'Alice', 'age': 30, and 'city': 'New York'.
Django
Need a hint?

Use curly braces {} to create a dictionary with the exact keys and values.

2
Set the status code variable
Create a variable called status_code and set it to the integer 200.
Django
Need a hint?

Just assign the number 200 to the variable status_code.

3
Write the Django view function
Write a Django view function called user_info that takes a request parameter and returns a JsonResponse with user_data as data and status=status_code.
Django
Need a hint?

Define a function with def user_info(request): and return JsonResponse(user_data, status=status_code).

4
Import JsonResponse
Add the import statement to import JsonResponse from django.http at the top of the file.
Django
Need a hint?

Use from django.http import JsonResponse at the top of your file.