Display the login form and handle the login action.
| 75 | name="dispatch", |
| 76 | ) |
| 77 | class LoginView(RedirectURLMixin, FormView): |
| 78 | """ |
| 79 | Display the login form and handle the login action. |
| 80 | """ |
| 81 | |
| 82 | form_class = AuthenticationForm |
| 83 | authentication_form = None |
| 84 | template_name = "registration/login.html" |
| 85 | redirect_authenticated_user = False |
| 86 | extra_context = None |
| 87 | |
| 88 | def dispatch(self, request, *args, **kwargs): |
| 89 | if self.redirect_authenticated_user and self.request.user.is_authenticated: |
| 90 | redirect_to = self.get_success_url() |
| 91 | if redirect_to == self.request.path: |
| 92 | raise ValueError( |
| 93 | "Redirection loop for authenticated user detected. Check that " |
| 94 | "your LOGIN_REDIRECT_URL doesn't point to a login page." |
| 95 | ) |
| 96 | return HttpResponseRedirect(redirect_to) |
| 97 | return super().dispatch(request, *args, **kwargs) |
| 98 | |
| 99 | def get_default_redirect_url(self): |
| 100 | """Return the default redirect URL.""" |
| 101 | if self.next_page: |
| 102 | return resolve_url(self.next_page) |
| 103 | else: |
| 104 | return resolve_url(settings.LOGIN_REDIRECT_URL) |
| 105 | |
| 106 | def get_form_class(self): |
| 107 | return self.authentication_form or self.form_class |
| 108 | |
| 109 | def get_form_kwargs(self): |
| 110 | kwargs = super().get_form_kwargs() |
| 111 | kwargs["request"] = self.request |
| 112 | return kwargs |
| 113 | |
| 114 | def form_valid(self, form): |
| 115 | """Security check complete. Log the user in.""" |
| 116 | auth_login(self.request, form.get_user()) |
| 117 | return HttpResponseRedirect(self.get_success_url()) |
| 118 | |
| 119 | def get_context_data(self, **kwargs): |
| 120 | context = super().get_context_data(**kwargs) |
| 121 | current_site = get_current_site(self.request) |
| 122 | context.update( |
| 123 | { |
| 124 | self.redirect_field_name: self.get_redirect_url(), |
| 125 | "site": current_site, |
| 126 | "site_name": current_site.name, |
| 127 | **(self.extra_context or {}), |
| 128 | } |
| 129 | ) |
| 130 | return context |
| 131 | |
| 132 | |
| 133 | @method_decorator([csrf_protect, never_cache], name="dispatch") |