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
- Set up user registration, login, and logout.
- Protect your post creation views so only logged-in users can create posts.
- Display the logged-in user's name in the navigation.