How can I not use Django's admin login view?

2019-02-04 06:45发布

I created my own view for login. However if a user goes directly to /admin it brings them to the admin login page and doesn't use my custom view. How can I make it redirect to the login view used for everything not /admin?

9条回答
不美不萌又怎样
2楼-- · 2019-02-04 07:09

This is my solution with custom AdminSite class:

class AdminSite(admin.AdminSite):

    def _is_login_redirect(self, response):
        if isinstance(response, HttpResponseRedirect):
            login_url = reverse('admin:login', current_app=self.name)
            response_url = urllib.parse.urlparse(response.url).path
            return login_url == response_url
        else:
            return False

    def admin_view(self, view, cacheable=False):
        inner = super().admin_view(view, cacheable)

        def wrapper(request, *args, **kwargs):
            response = inner(request, *args, **kwargs)
            if self._is_login_redirect(response):
                if request.user.is_authenticated():
                    return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
                else:
                    return redirect_to_login(request.get_full_path(), reverse('accounts_login'))
            else:
                return response

        return wrapper
查看更多
淡お忘
3楼-- · 2019-02-04 07:16

Holá
I found a very simple solution.
Just tell django that the url for admin login is handle by your own login view

You just need to modify the urls.py fle of the project (note, not the application one)

  1. In your PROJECT folder locate the file urls.py.
  2. Add this line to the imports section
    from your_app_name import views
  3. Locate this line
    url(r'^admin/', include(admin.site.urls))
  4. Add above that line the following
    url(r'^admin/login/', views.your_login_view),

This is an example

    from django.conf.urls import include, url
    from django.contrib import admin

    from your_app import views

    urlpatterns = [
        url(r'^your_app_start/', include('your_app.urls',namespace="your_app_name")),

        url(r'^admin/login/', views.your_app_login),
        url(r'^admin/', include(admin.site.urls)),
    ]
查看更多
萌系小妹纸
4楼-- · 2019-02-04 07:21

While @Isaac's solution should reject majority of malicious bots, it doesn't provide protection for professional penetrating. As a logged in user gets the following message when trying to login to admin:

Django re-login prompt

We should instead use the admin decorator to reject all non-privileged users:

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import admin
[ ... ]
admin.site.login = staff_member_required(admin.site.login)

To the best of my knowledge, the decorator was added in 1.9.

查看更多
登录 后发表回答