NelsonLabs
Django/Authentication

Authentication

Django ships with a complete authentication system โ€” user registration, login, logout, password reset, groups, and permissions. You get all of this for free.

Using Django's built-in auth views
python
# myproject/urls.py
from django.contrib.auth import views as auth_views

urlpatterns = [
    # Built-in login/logout โ€” just wire them up
    path("login/",  auth_views.LoginView.as_view(template_name="auth/login.html"), name="login"),
    path("logout/", auth_views.LogoutView.as_view(), name="logout"),

    # Password reset (sends email with reset link)
    path("password-reset/", auth_views.PasswordResetView.as_view(), name="password-reset"),
]
Protecting views and working with the current user
python
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins    import LoginRequiredMixin

# Decorator โ€” redirect to login if not authenticated
@login_required
def dashboard(request):
    courses = request.user.enrolled_courses.all()
    return render(request, "dashboard.html", {"courses": courses})

# Check in the view
def profile(request):
    if not request.user.is_authenticated:
        return redirect("login")
    return render(request, "profile.html", {"user": request.user})

# In templates โ€” automatically available
# {% if user.is_authenticated %}
# {{ user.username }} {{ user.email }}
# {% endif %}