在管理员中添加用户时,Django AssertionError“sensitive_post_parameters未收到HttpRequest”

前端之家收集整理的这篇文章主要介绍了在管理员中添加用户时,Django AssertionError“sensitive_post_parameters未收到HttpRequest”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的Django 1.5应用程序(托管在webfaction上)中有自定义用户模型,我得到:
AssertionError at /admin/users/user/add/

sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod,be sure to use @method_decorator.

在本地,它可以正常使用django runserver命令.(更新:它在本地工作,因为我在本地使用Django 1.5.2,我在webfaction上安装了Django 1.5.4,这只是在1.5.4中引发的异常)

任何帮助表示赞赏.谢谢

这是跟踪:

Environment:


Request Method: GET
Request URL: http://lts-demo.hashcode.pw/admin/users/user/add/

Django Version: 1.5.4
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.staticfiles','django.contrib.admin','south','crumbs','compressor','apps.users','apps.leaves','apps.messaging')
Installed Middleware:
('django.middleware.common.CommonMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/core/handlers/base.py" in get_response
  115.                         response = callback(request,*callback_args,**callback_kwargs)
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/contrib/admin/options.py" in wrapper
  372.                 return self.admin_site.admin_view(view)(*args,**kwargs)
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request,*args,**kwargs)
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/views/decorators/cache.py" in _wrapped_view_func
  89.         response = view_func(request,**kwargs)
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/contrib/admin/sites.py" in inner
  202.             return view(request,**kwargs)
File "/home/mnazim/webapps/dcleh_lts/lib/python2.7/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  68.               "sensitive_post_parameters didn't receive an HttpRequest. If you "

Exception Type: AssertionError at /admin/users/user/add/
Exception Value: sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod,be sure to use @method_decorator.

编辑:添加模型和admin.py

这是users / models.py

from django.conf import settings
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser,BaseUserManager,Group,Permission,_user_has_module_perms,_user_has_perm)
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone

from apps.helpers import values_to_choices,choices_to_values

class User(AbstractBaseUser):
    username = models.CharField(max_length=128,unique=True)
    email = models.CharField(_('email address'),max_length=256,unique=True)
    name = models.CharField(max_length=512,blank=True)
    mobile_no = models.CharField(_('mobile number'),max_length=10)

    department = models.CharField(max_length=512)
    post = models.CharField(max_length=512)
    posting_location = models.CharField(max_length=512)
    district = models.CharField(max_length=16,choices=DISTRICT_CHOICES)

    can_recommend_leaves = models.BooleanField(default=True,help_text='Designates whether user can recommend leaves')
    can_approve_leaves = models.BooleanField(default=False,help_text='Designates whether user can approve leaves')

    is_staff = models.BooleanField(_('staff status'),default=False,help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'),default=True,help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    is_superuser = models.BooleanField(_('superuser status'),help_text=_('Designates that this user has all permissions without '
                    'explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'),default=timezone.now)
    groups = models.ManyToManyField(Group,verbose_name=_('groups'),related_name='users',blank=True,help_text=_('The groups this user belongs to. A user will '
                                'get all permissions granted to each of '
                                'his/her group.'))
    user_permissions = models.ManyToManyField(Permission,verbose_name=_('user permissions'),help_text='Specific permissions for this user.')

    objects = UserManager()

    USERNAME_FIELD = 'username'
    required_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        db_table = 'users'

    def __unicode__(self):
        return "%s - %s(%s)" % (self.name,self.post,self.department)
        return self.name or self.username

    def get_absolute_url(self):
        return "/~%s/" % (self.username)

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        "Returns the short name for the user."
        return self.name

    def get_group_permissions(self,obj=None):
        """
        Returns a list of permission strings that this user has through his/her
        groups. This method queries all available auth backends. If an object
        is passed in,only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend,"get_group_permissions"):
                if obj is not None:
                    permissions.update(backend.get_group_permissions(self,obj))
                else:
                    permissions.update(backend.get_group_permissions(self))
        return permissions

    def get_all_permissions(self,obj=None):
        return _user_get_all_permissions(self,obj)

    def has_perm(self,perm,obj=None):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends,but returns immediately if any
        backend returns True. Thus,a user who has permission from a single
        auth backend is assumed to have permission in general. If an object is
        provided,permissions for this specific object are checked.
        """

        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        return _user_has_perm(self,obj)

    def has_perms(self,perm_list,obj=None):
        """
        Returns True if the user has each of the specified permissions. If
        object is passed,it checks if the user has all required perms for this
        object.
        """
        for perm in perm_list:
            if not self.has_perm(perm,obj):
                return False
        return True

    def has_module_perms(self,app_label):
        """
        Returns True if the user has any permissions in the given app label.
        Uses pretty much the same logic as has_perm,above.
        """
        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        return _user_has_module_perms(self,app_label)

    def email_user(self,subject,message,from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject,from_email,[self.email])

这是users / admin.py

from django.db import transaction
from django.contrib import admin
from django.contrib.auth.forms import (UserCreationForm,UserChangeForm,AdminPasswordChangeForm)
from django.utils.translation import ugettext,ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import get_object_or_404
from django.utils.html import escape
from django.template.response import TemplateResponse
from django.contrib import messages
from django.http import HttpResponseRedirect,Http404

from .models import User
# Overridden UserChangeForm and UserCreationForm for customized User model
from .forms import UserChangeForm,UserCreationForm

csrf_protect_m = method_decorator(csrf_protect)


class UserAdmin(admin.ModelAdmin):
    add_form_template = 'admin/auth/user/add_form.html'
    change_user_password_template = None
    #fieldsets = (
        #(None,{'fields': ('username','password')}),#(_('Personal info'),{'fields': ('first_name','last_name','email')}),#(_('Permissions'),{'fields': ('is_active','is_staff','is_superuser',#'groups','user_permissions')}),#(_('Important dates'),{'fields': ('last_login','date_joined')}),#)
    add_fieldsets = (
        (None,{
            'classes': ('wide',),'fields': ('username','password1','password2','email')}
        ),)
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm
    list_display = ('name','username','email','is_staff')
    list_filter = ('is_staff','is_active','groups')
    search_fields = ('name','first_name','email')
    ordering = ('username',)
    filter_horizontal = ('groups','user_permissions',)

    def get_fieldsets(self,request,obj=None):
        if not obj:
            return self.add_fieldsets
        return super(UserAdmin,self).get_fieldsets(request,obj)

    def get_form(self,obj=None,**kwargs):
        """
        Use special form during user creation
        """
        defaults = {}
        if obj is None:
            defaults.update({
                'form': self.add_form,'fields': admin.util.flatten_fieldsets(self.add_fieldsets),})
        defaults.update(kwargs)
        return super(UserAdmin,self).get_form(request,obj,**defaults)

    def get_urls(self):
        from django.conf.urls import patterns
        return patterns('',(r'^(\d+)/password/$',self.admin_site.admin_view(self.user_change_password))
        ) + super(UserAdmin,self).get_urls()

    def lookup_allowed(self,lookup,value):
        # See #20078: we don't want to allow any lookups involving passwords.
        if lookup.startswith('password'):
            return False
        return super(UserAdmin,self).lookup_allowed(lookup,value)

    @sensitive_post_parameters()
    @csrf_protect_m
    @transaction.commit_on_success
    def add_view(self,form_url='',extra_context=None):
        # It's an error for a user to have add permission but NOT change
        # permission for users. If we allowed such users to add users,they
        # could create superusers,which would mean they would essentially have
        # the permission to change users. To avoid the problem entirely,we
        # disallow users from adding users if they don't have change
        # permission.
        if not self.has_change_permission(request):
            if self.has_add_permission(request) and settings.DEBUG:
                # Raise Http404 in debug mode so that the user gets a helpful
                # error message.
                raise Http404(
                    'Your user does not have the "Change user" permission. In '
                    'order to add users,Django requires that your user '
                    'account have both the "Add user" and "Change user" '
                    'permissions set.')
            raise PermissionDenied
        if extra_context is None:
            extra_context = {}
        username_field = self.model._Meta.get_field(self.model.USERNAME_FIELD)
        defaults = {
            'auto_populated_fields': (),'username_help_text': username_field.help_text,}
        extra_context.update(defaults)
        return super(UserAdmin,self).add_view(request,form_url,extra_context)

    @sensitive_post_parameters()
    def user_change_password(self,id,form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.queryset(request),pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user,request.POST)
            if form.is_valid():
                form.save()
                msg = ugettext('Password changed successfully.')
                messages.success(request,msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)

        fieldsets = [(None,{'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form,fieldsets,{})

        context = {
            'title': _('Change password: %s') % escape(user.get_username()),'adminForm': adminForm,'form_url': form_url,'form': form,'is_popup': '_popup' in request.REQUEST,'add': True,'change': False,'has_delete_permission': False,'has_change_permission': True,'has_absolute_url': False,'opts': self.model._Meta,'original': user,'save_as': False,'show_save': True,}
        return TemplateResponse(request,self.change_user_password_template or
            'admin/auth/user/change_password.html',context,current_app=self.admin_site.name)

    def response_add(self,post_url_continue=None):
        """
        Determines the HttpResponse for the add_view stage. It mostly defers to
        its superclass implementation but is customized because the User model
        has a slightly different workflow.
        """
        # We should allow further modification of the user just added i.e. the
        # 'Save' button should behave like the 'Save and continue editing'
        # button except in two scenarios:
        # * The user has pressed the 'Save and add another' button
        # * We are adding a user in a popup
        if '_addanother' not in request.POST and '_popup' not in request.POST:
            request.POST['_continue'] = 1
        return super(UserAdmin,self).response_add(request,post_url_continue)

admin.site.register(User,UserAdmin)

解决方法

错误消息非常清楚.
If you are decorating a classmethod,be sure to use @method_decorator.

在您的情况下,任何使用sensitive_post_parameters装饰器的模型管理方法都应该使用method_decorator.例如:

from django.utils.decorators import method_decorator

class UserAdmin(admin.ModelAdmin):
    ...

    @method_decorator(sensitive_post_parameters())
    @csrf_protect_m
    @transaction.commit_on_success
    def add_view(self,extra_context=None):

猜你在找的Python相关文章