`login_required` is Django’s built-in view decorator for the first gate of authorization: only authenticated users may enter the wrapped view. Put `@login_required` immediately above a view function. An authenticated request reaches the view normally; an anonymous request is redirected to a login page instead of running the view. section 6.3 section 6.8
Figure 6.4 Authentication verification steps for visiting a @login_required wrapped view
Follow the request path through authentication verification before the protected view is allowed to render its response. section 6.3
Protecting a simple page
Import the decorator from `django.contrib.auth.decorators`, then wrap a normal view. The decorator handles the access check while the view remains responsible only for preparing context and rendering its template. `@login_required` `def restricted_page(request):` ` data = {'title': 'Restricted Page', 'content': '<h1>You are logged in</h1>'}` ` return render(request, 'general.html', data)` Register a URL for the view and visit it while logged in and logged out. A logged-in user sees the page; an anonymous user is sent through the login flow. section 6.3 section 6.3
Authentication and authorization are related but different jobs. Authentication establishes who the user is; `login_required` performs the broad authorization check that the user is authenticated. It does not decide whether that user may access a particular musician, band, or other object. Add view-specific checks after the decorator when access depends on ownership, membership, or another relationship. section 6.1 section 6.4
A protected view commonly follows this sequence:
- Django session management establishes whether the request belongs to a logged-in user. section 6.1
- `login_required` permits an authenticated request to call the view, or redirects an anonymous request to login. section 6.3
- The view may inspect `request.user` and related profile data for object-specific authorization. section 6.4
- Reject unauthorized object access, such as a user who is neither the musician nor a bandmate, with `Http404`. section 6.4
The redirect needs a working login endpoint and template. Django can provide authentication URLs with `include('django.contrib.auth.urls')`; the login view still needs a site template at `templates/registration/login.html`. The template posts the login form with a CSRF token and renders Django’s supplied form fields. section 6.3 section 6.3
Use `login_required` as the outer access gate, not as a replacement for permissions. It is ideal when every account may use a page. When a page is private to a band or musician, authenticate first, fetch the requested object, then verify the relationship before returning content. This keeps the simple check simple and the business rule visible in the view. section 6.4 section 6.8
