0
0
Djangoframework~30 mins

Why authorization matters in Django - See It in Action

Choose your learning style9 modes available
Why authorization matters
📖 Scenario: You are building a simple Django web app where users can view their own profile information. Authorization ensures that users cannot see or change other users' profiles.
🎯 Goal: Create a Django view that only allows a logged-in user to access their own profile page. If a user tries to access another user's profile, they should be denied.
📋 What You'll Learn
Create a Django model called UserProfile with fields user (OneToOneField to User) and bio (TextField).
Create a view function called profile_view that takes request and username as parameters.
In profile_view, check if the logged-in user's username matches the username parameter to authorize access.
If authorized, render a template called profile.html with the user's profile data; otherwise, return HttpResponseForbidden.
💡 Why This Matters
🌍 Real World
Authorization is essential in web apps to protect user data and privacy by ensuring users only access what they are allowed to.
💼 Career
Understanding authorization is critical for backend developers and full-stack developers to build secure applications.
Progress0 / 4 steps
1
Create the UserProfile model
Create a Django model called UserProfile with a user field as a OneToOneField to auth.User and a bio field as a TextField.
Django
Need a hint?

Use models.OneToOneField to link to the User model and models.TextField for the bio.

2
Add the profile_view function
Create a view function called profile_view that takes request and username as parameters.
Django
Need a hint?

Define a function with the exact name profile_view and parameters request, username.

3
Check authorization inside profile_view
Inside profile_view, check if request.user.username equals the username parameter. If not equal, return HttpResponseForbidden(). Otherwise, get the UserProfile for that user.
Django
Need a hint?

Use an if statement to compare usernames and return HttpResponseForbidden() if they don't match.

4
Render the profile.html template
In profile_view, after authorization and fetching the profile, render the profile.html template passing the profile object in the context with key profile.
Django
Need a hint?

Use render to send the profile object to the template named profile.html.