|
4 | 4 |
|
5 | 5 | from django.conf import settings |
6 | 6 | from django.contrib import admin |
| 7 | +from django.contrib.auth import REDIRECT_FIELD_NAME |
7 | 8 | from django.contrib.auth.decorators import login_not_required |
8 | | -from django.http import HttpRequest, HttpResponse |
9 | | -from django.urls import path, reverse_lazy, URLPattern, URLResolver |
| 9 | +from django.http import HttpRequest, HttpResponse, HttpResponseRedirect |
| 10 | +from django.urls import path, reverse_lazy, URLPattern, URLResolver, reverse |
| 11 | +from django.utils.decorators import method_decorator |
| 12 | +from django.utils.translation import gettext_lazy as _ |
10 | 13 | from django.views.decorators.cache import never_cache |
11 | 14 | from django.views.decorators.csrf import csrf_protect |
12 | 15 | from django.views.generic import TemplateView |
@@ -195,5 +198,46 @@ def get_urls(self) -> list[URLPattern | URLResolver]: |
195 | 198 | urls.extend(super().get_urls()) |
196 | 199 | return urls |
197 | 200 |
|
| 201 | + @method_decorator(never_cache) |
| 202 | + @login_not_required |
| 203 | + def login(self, request: HttpRequest, extra_context: dict[str, Any] | None = None): |
| 204 | + """ |
| 205 | + Same as Django's built-in AdminSite.login view, except it allows the |
| 206 | + login view class to be overridden via configuration. |
| 207 | + """ |
| 208 | + if request.method == "GET" and self.has_permission(request): |
| 209 | + # Already logged-in, redirect to admin index |
| 210 | + index_path = reverse("admin:index", current_app=self.name) |
| 211 | + return HttpResponseRedirect(index_path) |
| 212 | + |
| 213 | + # Since this module gets imported in the application's root package, |
| 214 | + # it cannot import models from other applications at the module level, |
| 215 | + # and django.contrib.admin.forms eventually imports User. |
| 216 | + from django.contrib.admin.forms import AdminAuthenticationForm |
| 217 | + |
| 218 | + context = { |
| 219 | + **self.each_context(request), |
| 220 | + "title": _("Log in"), |
| 221 | + "subtitle": None, |
| 222 | + "app_path": request.get_full_path(), |
| 223 | + "username": request.user.get_username(), |
| 224 | + } |
| 225 | + if ( |
| 226 | + REDIRECT_FIELD_NAME not in request.GET |
| 227 | + and REDIRECT_FIELD_NAME not in request.POST |
| 228 | + ): |
| 229 | + context[REDIRECT_FIELD_NAME] = reverse("admin:index", current_app=self.name) |
| 230 | + context.update(extra_context or {}) |
| 231 | + |
| 232 | + defaults = { |
| 233 | + "extra_context": context, |
| 234 | + "authentication_form": self.login_form or AdminAuthenticationForm, |
| 235 | + "template_name": self.login_template or "admin/login.html", |
| 236 | + } |
| 237 | + request.current_app = self.name |
| 238 | + return request.request_data.configuration.login_view_class.as_view(**defaults)( |
| 239 | + request |
| 240 | + ) |
| 241 | + |
198 | 242 |
|
199 | 243 | sb_admin_site = SBAdminSite(name="sb_admin") |
0 commit comments