Django需多验证类视图中三类Mixin的继承顺序问询
Correct Inheritance Order for Django's LoginRequiredMixin, PermissionRequiredMixin, and OTPRequiredMixin
Great question—Mixin order in Django class-based views is crucial because it determines the order of execution for their dispatch methods (the entry point for processing requests). Here's the correct inheritance sequence, along with the reasoning behind it:
The Valid Inheritance Sequence
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from two_factor.views.mixins import OTPRequiredMixin from django.views.generic import TemplateView # Example base view (adjust as needed) class SecuredView(LoginRequiredMixin, OTPRequiredMixin, PermissionRequiredMixin, TemplateView): # View configuration goes here permission_required = "your_app.your_target_permission" # Replace with your actual permission string
Why This Order Makes Sense
We follow Django’s Method Resolution Order (MRO), which runs mixin logic from left to right. Here’s the breakdown of each step:
- LoginRequiredMixin (leftmost): As the official Django docs specify, this must be first. It checks if the user is authenticated—if not, it immediately redirects to the login page. This ensures all subsequent validation steps only run for logged-in users, avoiding unnecessary checks for unauthenticated visitors.
- OTPRequiredMixin: Next, we validate that the user has completed two-factor authentication. This mixin relies on an already authenticated user (handled by the first mixin), so placing it right after
LoginRequiredMixinensures we don’t attempt to check 2FA for a user who isn’t logged in. If the user hasn’t completed OTP verification, they’ll be redirected to the 2FA setup/verification flow. - PermissionRequiredMixin: Finally, we check if the authenticated, 2FA-verified user has the necessary permissions to access the view. Permission checks depend on a valid, authenticated user object, so this step comes last in the validation chain. If the user lacks permissions, they’ll get a 403 Forbidden response or be redirected (depending on your setup).
- Base View (rightmost): Your core view class (like
TemplateView,DetailView, etc.) goes last. It runs only after all validation steps have passed, ensuring the view logic executes only for authorized users.
What Happens If You Get the Order Wrong?
- If you place
PermissionRequiredMixinbeforeLoginRequiredMixin, the permission check will run for unauthenticated users, leading to confusing behavior (like a 403 page instead of a login redirect). - If you put
OTPRequiredMixinbeforeLoginRequiredMixin, the 2FA check will try to access a user object that doesn’t exist (since the user isn’t logged in), causing errors.
内容的提问来源于stack exchange,提问作者Kurt Peek
相关产品推荐
相关产品推荐

