In Django, mixins provide a flexible and reusable way to add common functionality to class-based views (CBVs). Mixins are small, reusable classes that enhance views without duplicating code.
A mixin is a class that provides specific functionality to other classes through inheritance. Mixins encapsulate shared behavior and are commonly used with CBVs.
Django provides several built-in mixins for authentication, permissions, and form handling. You can also define your own custom mixins.
# Ensures only authenticated users can access the view
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class ProfileView(LoginRequiredMixin, TemplateView):
template_name = 'profile.html'
# Restricts access based on specific permissions
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import TemplateView
class AdminView(PermissionRequiredMixin, TemplateView):
template_name = 'admin.html'
permission_required = 'auth.view_user'
# Handles form creation and validation logic
from django.views.generic.edit import FormMixin
from django.views.generic import TemplateView
from .forms import BookForm
class BookCreateView(FormMixin, TemplateView):
template_name = 'book_form.html'
form_class = BookForm
success_url = '/books/'
# Custom reusable behavior added to views
class CustomMixin:
def custom_method(self):
print("This is a custom method!")
Check the boxes to see how mixins change the class definition and the order of execution (MRO).