【问题标题】:Django 1.7 admin for non-staff users非员工用户的 Django 1.7 管理员
【发布时间】:2015-03-06 08:33:13
【问题描述】:

在之前的项目中(使用 Django 1.5),我使用自定义的 Django 管理站点为非员工用户提供对有限模型子集的访问。我使用了here 提供的出色解释。这就像一个魅力。

对于一个新项目,我使用的是 Django 1.7,并且我了解到 check_for_test_cookie() 已被弃用。但是,仅将其注释掉似乎并不能提供所需的功能。当我尝试使用员工和非员工帐户登录我的 user_admin 站点时出现错误。我收到的错误消息“请更正下面的错误”并没有给我任何额外的线索。

关于如何在 Django 1.7 中进行这项工作的任何建议?我的代码如下。

myapp/user_admin.py

from __future__ import unicode_literals

from django.contrib.auth.models import User
from django.contrib.admin.sites import AdminSite
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy
from django.utils.translation import ugettext as _

ERROR_MESSAGE = ugettext_lazy("Please enter the correct %(username)s and password "
        "for a staff account. Note that both fields may be case-sensitive.")
class UserAdminAuthenticationForm(AuthenticationForm):
    """
    Same as Django's AdminAuthenticationForm but allows to login
    any user who is not staff.
    """
    this_is_the_login_form = forms.BooleanField(widget=forms.HiddenInput,
                                initial=1,
                                error_messages={'required': ugettext_lazy(
                                "Please log in again, because your session has"
                                " expired.")})

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(username=username,
            password=password)
            if self.user_cache is None:
                if u'@' in username:
                    # Mistakenly entered e-mail address instead of username?
                    # Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your "
                                        "username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            # Removed check for is_staff here!
            elif not self.user_cache.is_active:
                raise forms.ValidationError(message)
        #self.check_for_test_cookie()
        return self.cleaned_data

class UserAdmin(AdminSite):

    login_form = UserAdminAuthenticationForm

    def has_permission(self, request):
        """
        Removed check for is_staff.
        """
        return request.user.is_active

user_admin_site = UserAdmin(name='usersadmin')

urls.py

from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from myapp.user_admin import user_admin_site
from mypapp.models import *
from myapp.admin import *

admin.autodiscover()
admin.site.register(mystaffmodel,mystaffmodel_admin)

user_admin_site.register(mynonstaffmodel,mynonstaffmodel_admin)

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

【问题讨论】:

  • 经过反复试验,我发现this 解决了这个问题。它似乎与重定向 URL 有关。

标签: django-admin django-1.7


【解决方案1】:

您的表单必须如下所示

from __future__ import unicode_literals
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group, Permission


class UserAdminAuthenticationForm(AuthenticationForm):
    def confirm_login_allowed(self, user):    
        if not user.is_active:    
            raise forms.ValidationError(    
                _("This account is inactive."),    
               code='inactive',    
            )

足以运行您的代码。 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 2016-04-08
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多