Junior — Middle
Can you explain the purpose and principle of operation of the LoginRequiredMixin in Django?
sobes.tech AI
Answer from AI
LoginRequiredMixin is a mixin from Django used to restrict access to class-based views only to authenticated users.
How it works:
- When attempting to access the view, it checks whether the user is authenticated.
- If the user is not logged in, it redirects to the login page.
- If the user is authenticated, access to the view is granted.
Example of usage:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class MyView(LoginRequiredMixin, TemplateView):
template_name = 'my_template.html'
Thus, LoginRequiredMixin simplifies protecting views from unauthorized access without the need to write additional check code.