如何不使用Django的admin登录视图?

时间:2022-06-02 07:22:22

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?

我创建了自己的登录视图。但是,如果用户直接访问/admin,它会将用户带到admin登录页面,而不使用我的自定义视图。如何使它重定向到所有非/admin的登录视图?

8 个解决方案

#1


48  

From http://djangosnippets.org/snippets/2127/—wrap the admin login page with login_required. For example, in urls.py:

从http://djangosnippets.org/snippets/2127/-用login_required包装admin登录页面。例如,在urls . py:

from django.contrib.auth.decorators import login_required
from django.contrib import admin
admin.autodiscover()
admin.site.login = login_required(admin.site.login)

You probably already have the middle two lines and maybe even the first line; adding that fourth line will cause anything that would have hit the admin.site.login function to redirect to your LOGIN_URL with the appropriate next parameter.

你可能已经有了中间的两行甚至是第一行;添加第4行将导致任何可能会影响admin.site的内容。登录函数,以使用适当的下一个参数重定向到LOGIN_URL。

#2


4  

I found that the answer above does not respect the "next" query parameter correctly.

我发现上面的答案并不正确地尊重“下一个”查询参数。

An easy way to solve this problem is to use a simple redirect. In your site's urls file, immediately before including the admin urls, put a line like this:

解决这个问题的一个简单方法是使用简单的重定向。在您的站点的url文件中,在包含管理url之前,在下面这样一行:

   url(r'^admin/login$', RedirectView.as_view(pattern_name='my_login_page', permanent=True, query_string=True))

#3


3  

http://blog.montylounge.com/2009/07/5/customizing-django-admin-branding/ (web archive)

http://blog.montylounge.com/2009/07/5/customizing-django-admin-branding/(web存档)

I'm trying to solve exactly this problem and I found the solution at this guys blog. Basically, override the admin template and use your own template. In short, just make a file called login.html in /path-to-project/templates/admin/ and it will replace the admin login page. You can copy the original (django/contrib/admin/templates/login.html) and modify a line or two. If you want to scrap the default login page entirely you can do something like this:

我正试图解决这个问题我在这个博客上找到了解决办法。基本上,重写管理模板并使用您自己的模板。简而言之,只需创建一个名为login的文件。html in/ path-to-project/template /admin/中,它将取代admin登录页面。您可以复制原始(django/悔过书/admin/template /login.html)并修改一两行。如果你想完全废弃默认的登录页面,你可以这样做:

{% extends "my-login-page.html" %}

There it is. One line in one file. Django is amazing.

在这里。一个文件中的一行。Django是惊人的。

#4


3  

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

我找到了一个很简单的解决办法。只需告诉django, admin登录的url是由您自己的登录视图处理的

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

只需修改url即可。项目的重要性(注意,不是应用程序)

  1. In your PROJECT folder locate the file urls.py.
  2. 在项目文件夹中找到文件url .py。
  3. Add this line to the imports section
    from your_app_name import views
  4. 从your_app_name导入视图中向导入部分添加这一行。
  5. Locate this line
    url(r'^admin/', include(admin.site.urls))
  6. 这条线定位url(r ^ admin /,包括(admin.site.urls))
  7. Add above that line the following
    url(r'^admin/login/', views.your_login_view),
  8. 上面添加这条线以下url(r ^ admin /登录/,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)),
    ]

#5


3  

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:

虽然@Isaac的解决方案应该会拒绝大多数恶意软件,但并没有为专业的入侵提供保护。当登录时,用户在试图登录到admin时得到以下信息:

如何不使用Django的admin登录视图?

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

相反,我们应该使用admin decorator来拒绝所有非特权用户:

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.

据我所知,在1.9中添加了decorator。

#6


2  

In your ROOT_URLCONF file (by default, it's urls.py in the project's root folder), is there a line like this:

在ROOT_URLCONF文件中(默认情况下,它是url)。项目根文件夹中的py),是否有如下一行:

urlpatterns = patterns('',
...
    (r'^admin/', include(admin.site.urls)),
...
)

If so, you'd want to replace include(admin.site.urls) with the custom view you created:

如果是这样,您需要使用创建的自定义视图替换include(admin.site.url):

(r'^admin/', 'myapp.views.myloginview'),

or if your app has its own urls.py, you could include it like this:

或者如果你的应用有自己的url。py,你可以这样写:

(r'^admin/', include(myapp.urls)),

#7


1  

This is my solution with custom AdminSite class:

这是我的自定义AdminSite类解决方案:

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

#8


0  

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)

其思想是,如果用户正在登录,并试图访问管理员,那么他将获得404。否则,它将强制您登录到正常的登录页面(除非您已经登录)

#1


48  

From http://djangosnippets.org/snippets/2127/—wrap the admin login page with login_required. For example, in urls.py:

从http://djangosnippets.org/snippets/2127/-用login_required包装admin登录页面。例如,在urls . py:

from django.contrib.auth.decorators import login_required
from django.contrib import admin
admin.autodiscover()
admin.site.login = login_required(admin.site.login)

You probably already have the middle two lines and maybe even the first line; adding that fourth line will cause anything that would have hit the admin.site.login function to redirect to your LOGIN_URL with the appropriate next parameter.

你可能已经有了中间的两行甚至是第一行;添加第4行将导致任何可能会影响admin.site的内容。登录函数,以使用适当的下一个参数重定向到LOGIN_URL。

#2


4  

I found that the answer above does not respect the "next" query parameter correctly.

我发现上面的答案并不正确地尊重“下一个”查询参数。

An easy way to solve this problem is to use a simple redirect. In your site's urls file, immediately before including the admin urls, put a line like this:

解决这个问题的一个简单方法是使用简单的重定向。在您的站点的url文件中,在包含管理url之前,在下面这样一行:

   url(r'^admin/login$', RedirectView.as_view(pattern_name='my_login_page', permanent=True, query_string=True))

#3


3  

http://blog.montylounge.com/2009/07/5/customizing-django-admin-branding/ (web archive)

http://blog.montylounge.com/2009/07/5/customizing-django-admin-branding/(web存档)

I'm trying to solve exactly this problem and I found the solution at this guys blog. Basically, override the admin template and use your own template. In short, just make a file called login.html in /path-to-project/templates/admin/ and it will replace the admin login page. You can copy the original (django/contrib/admin/templates/login.html) and modify a line or two. If you want to scrap the default login page entirely you can do something like this:

我正试图解决这个问题我在这个博客上找到了解决办法。基本上,重写管理模板并使用您自己的模板。简而言之,只需创建一个名为login的文件。html in/ path-to-project/template /admin/中,它将取代admin登录页面。您可以复制原始(django/悔过书/admin/template /login.html)并修改一两行。如果你想完全废弃默认的登录页面,你可以这样做:

{% extends "my-login-page.html" %}

There it is. One line in one file. Django is amazing.

在这里。一个文件中的一行。Django是惊人的。

#4


3  

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

我找到了一个很简单的解决办法。只需告诉django, admin登录的url是由您自己的登录视图处理的

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

只需修改url即可。项目的重要性(注意,不是应用程序)

  1. In your PROJECT folder locate the file urls.py.
  2. 在项目文件夹中找到文件url .py。
  3. Add this line to the imports section
    from your_app_name import views
  4. 从your_app_name导入视图中向导入部分添加这一行。
  5. Locate this line
    url(r'^admin/', include(admin.site.urls))
  6. 这条线定位url(r ^ admin /,包括(admin.site.urls))
  7. Add above that line the following
    url(r'^admin/login/', views.your_login_view),
  8. 上面添加这条线以下url(r ^ admin /登录/,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)),
    ]

#5


3  

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:

虽然@Isaac的解决方案应该会拒绝大多数恶意软件,但并没有为专业的入侵提供保护。当登录时,用户在试图登录到admin时得到以下信息:

如何不使用Django的admin登录视图?

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

相反,我们应该使用admin decorator来拒绝所有非特权用户:

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.

据我所知,在1.9中添加了decorator。

#6


2  

In your ROOT_URLCONF file (by default, it's urls.py in the project's root folder), is there a line like this:

在ROOT_URLCONF文件中(默认情况下,它是url)。项目根文件夹中的py),是否有如下一行:

urlpatterns = patterns('',
...
    (r'^admin/', include(admin.site.urls)),
...
)

If so, you'd want to replace include(admin.site.urls) with the custom view you created:

如果是这样,您需要使用创建的自定义视图替换include(admin.site.url):

(r'^admin/', 'myapp.views.myloginview'),

or if your app has its own urls.py, you could include it like this:

或者如果你的应用有自己的url。py,你可以这样写:

(r'^admin/', include(myapp.urls)),

#7


1  

This is my solution with custom AdminSite class:

这是我的自定义AdminSite类解决方案:

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

#8


0  

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)

其思想是,如果用户正在登录,并试图访问管理员,那么他将获得404。否则,它将强制您登录到正常的登录页面(除非您已经登录)