0
0
Djangoframework~30 mins

login_required decorator in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the login_required Decorator in Django
📖 Scenario: You are building a simple Django web app where some pages should only be seen by users who have logged in. To protect these pages, you will use Django's login_required decorator.
🎯 Goal: Learn how to use the login_required decorator to restrict access to a view so that only logged-in users can see it.
📋 What You'll Learn
Create a Django view function named dashboard that returns a simple HTTP response.
Import and use the login_required decorator from django.contrib.auth.decorators.
Apply the login_required decorator to the dashboard view.
Add a URL pattern for the dashboard view in urls.py.
💡 Why This Matters
🌍 Real World
Many websites have pages that only logged-in users should see, like user dashboards, profiles, or settings. Protecting these pages is important for privacy and security.
💼 Career
Understanding how to restrict access to parts of a web app is a key skill for web developers working with Django or any web framework.
Progress0 / 4 steps
1
Create the dashboard view function
In your Django app's views.py, create a function called dashboard that takes a request parameter and returns an HttpResponse with the text "Welcome to your dashboard!". Import HttpResponse from django.http.
Django
Need a hint?

Remember to import HttpResponse and define a function named dashboard that returns it with the welcome text.

2
Import the login_required decorator
In views.py, add an import statement to import login_required from django.contrib.auth.decorators.
Django
Need a hint?

Use from django.contrib.auth.decorators import login_required to import the decorator.

3
Apply the login_required decorator to the dashboard view
Add the @login_required decorator above the dashboard function definition in views.py.
Django
Need a hint?

Place @login_required directly above the dashboard function.

4
Add a URL pattern for the dashboard view
In your app's urls.py, import the dashboard view and add a URL pattern for path dashboard/ that points to the dashboard view. Import path from django.urls.
Django
Need a hint?

Use path('dashboard/', dashboard, name='dashboard') inside urlpatterns.