Protect Your Views
Use the auth decorator to protect authenticated views.
The require_session decorator protects Django views by verifying active user sessions, automatically redirecting unauthenticated users to the login screen. It should be applied to all protected views to ensure secure access. For detailed implementation, see the Wristband documentation.
Redirect Behavior for Template ViewsThis guide uses server-side templates, so the decorator is configured with
UnauthenticatedBehavior.REDIRECT— it redirects unauthenticated users to your Login Endpoint. For API views that return JSON, create an additional decorator withUnauthenticatedBehavior.JSONinstead, which returns a 401 Unauthorized response.
Using the Auth Decorator to Protect Views
To protect your views, place the @require_session decorator directly above the view functions that require a logged-in user.
# your_app/protected_views.py
from django.shortcuts import render
from .wristband import require_session
@require_session
def dashboard(request):
"""Protected view - only accessible to authenticated users"""
return render(request, 'dashboard.html')When a logged-out user tries to open a protected page, the app stops them and sends them straight to the login screen.
Add Auth-Aware Rendering to Templates
For public pages, use conditional logic inside the view to display unique content based on whether a visitor is logged in or out.
# your_app/views.py
def home(request):
"""Public home page with conditional UI"""
return render(request, 'home.html', {
'is_authenticated': request.session.get('is_authenticated', False),
'email': request.session.get('email'),
})Use the is_authenticated variable in your template to render different content for authenticated and unauthenticated users. For example, show login links for unauthenticated users and logout links for authenticated ones:
<!-- Example: your_app/templates/base.html -->
{% if is_authenticated %}
<p>Welcome, {{ email }}!</p>
<a href="{% url 'your_app:logout' %}">Logout</a>
{% else %}
<a href="{% url 'your_app:login' %}">Login</a>
{% endif %}Updated 6 days ago
What’s Next
Now that you've finished protecting your views, let's run some final tests to ensure everything is working.