0
0
Djangoframework~30 mins

HttpRequest object in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Django HttpRequest Object
📖 Scenario: You are building a simple Django web app that greets users by their name passed in the URL query parameters.
🎯 Goal: Create a Django view function that uses the HttpRequest object to read a user's name from the query string and returns a greeting message.
📋 What You'll Learn
Create a Django view function named greet_user that accepts a request parameter
Use the request.GET dictionary to get the value of the name query parameter
Set a default name of 'Guest' if the name parameter is missing
Return an HttpResponse with the greeting message 'Hello, <name>!'
Ensure the view function handles the HttpRequest object correctly
💡 Why This Matters
🌍 Real World
Web developers often need to read user input from URLs to customize responses, such as greeting users by name or filtering content.
💼 Career
Understanding the HttpRequest object and how to extract data from it is fundamental for backend web development with Django.
Progress0 / 4 steps
1
Create the Django view function skeleton
Write a Django view function named greet_user that takes a single parameter called request.
Django
Need a hint?

Start by defining a function with the exact name greet_user and one parameter request.

2
Extract the 'name' parameter from the HttpRequest
Inside the greet_user function, create a variable called user_name that gets the 'name' value from request.GET. Use 'Guest' as the default if 'name' is not provided.
Django
Need a hint?

Use request.GET.get('name', 'Guest') to safely get the query parameter with a default.

3
Create the greeting message
Still inside the greet_user function, create a variable called message that uses an f-string to format the greeting: 'Hello, <user_name>!'.
Django
Need a hint?

Use an f-string like f'Hello, {user_name}!' to create the message.

4
Return the HttpResponse with the greeting
Complete the greet_user function by returning an HttpResponse object initialized with the message variable.
Django
Need a hint?

Use return HttpResponse(message) to send the response back to the browser.