0
0
Djangoframework~30 mins

Redirects with redirect function in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Redirects with redirect function
📖 Scenario: You are building a simple Django web app that needs to send users from one page to another automatically.For example, after a user visits a welcome page, you want to send them to the homepage.
🎯 Goal: Learn how to use Django's redirect function to send users from one view to another.You will create a view that redirects to another URL.
📋 What You'll Learn
Create a Django view function named welcome_view that redirects to the URL path /home/ using the redirect function.
Import the redirect function from django.shortcuts.
Create a second view function named home_view that returns a simple HTTP response with the text "Welcome Home!".
Add URL patterns for /welcome/ and /home/ paths pointing to welcome_view and home_view respectively.
💡 Why This Matters
🌍 Real World
Redirects are common in web apps to guide users after actions like login, logout, or form submission.
💼 Career
Understanding redirects is essential for backend web developers working with Django to control user navigation flow.
Progress0 / 4 steps
1
Create the home view
Create a Django view function called home_view that returns an HttpResponse with the text "Welcome Home!". Import HttpResponse from django.http.
Django
Need a hint?

Use def home_view(request): to define the view and return HttpResponse("Welcome Home!").

2
Import redirect function
Import the redirect function from django.shortcuts in the same file where home_view is defined.
Django
Need a hint?

Write from django.shortcuts import redirect at the top of the file.

3
Create the welcome view with redirect
Create a Django view function called welcome_view that uses the redirect function to send the user to the URL path /home/.
Django
Need a hint?

Define welcome_view and return redirect('/home/') inside it.

4
Add URL patterns for both views
In your Django urls.py file, import both welcome_view and home_view. Then add URL patterns for /welcome/ mapped to welcome_view and /home/ mapped to home_view. Import path from django.urls.
Django
Need a hint?

Use path('welcome/', welcome_view) and path('home/', home_view) inside urlpatterns.