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

后端 未结 10 2651
借酒劲吻你
借酒劲吻你 2020-12-28 15:11

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

相关标签:
10条回答
  • 2020-12-28 15:29

    As of August 2020, django.contrib.admin.sites.AdminSite has a login_template attribute. So you can just subclass AdminSite and specify a custom template i.e.,

    class MyAdminSite(AdminSite):
        login_template = 'my_login_template.html'
    
    my_admin_site = MyAdminSite()
    

    Then just use my_admin_site everywhere instead of admin.site.

    0 讨论(0)
  • 2020-12-28 15:30

    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)),
        ]
    
    0 讨论(0)
  • 2020-12-28 15:30

    I had the same issue, tried to use the accepted answer, but has the same issue as pointed in the comment above. Then I've did something bit different, pasting here if this would be helpful to someone.

    def staff_or_404(u):
        if u.is_active:
            if u.is_staff:
                return True
            raise Http404()
        return False
    
    admin.site.login = user_passes_test(
            staff_or_404,
        )(admin.site.login)
    

    The idea is that if the user is login, and tried to access the admin, then he gets 404. Otherwise, it will force you to the normal login page (unless you are already logged in)

    0 讨论(0)
  • 2020-12-28 15:32

    You can redirect admin login url to the auth login view :

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('', include('your_app.urls')),
        path('accounts/', include('django.contrib.auth.urls')),
        path('admin/login/', RedirectView.as_view(url='/accounts/login/?next=/admin/', permanent=True)),
        path('admin/', admin.site.urls),
    ]
    
    0 讨论(0)
提交回复
热议问题