Menu

Authentication

Introduction

Django includes a robust authentication system out of the box — user registration, login, logout, password reset, and permissions are all built in.

Built-in authentication

# settings.py
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

# urls.py
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

# Protecting views
from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

# In class-based views
from django.contrib.auth.mixins import LoginRequiredMixin

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'body']

Assignment

  1. Set up user registration, login, and logout.
  2. Protect your post creation views so only logged-in users can create posts.
  3. Display the logged-in user's name in the navigation.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!