Python 'WSGIRequest' 对象没有属性 'user' Django admin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37949198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:08:13  来源:igfitidea点击:

'WSGIRequest' object has no attribute 'user' Django admin

pythondjangoadminpanelwsgi

提问by Gon?alo Correia

When I trying to access the admin page it gives me the following error:

当我尝试访问管理页面时,它给了我以下错误:

System check identified no issues (0 silenced).
June 21, 2016 - 15:26:14
Django version 1.9.7, using settings 'librato_chart_sender_web.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /admin/
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py", line 265, in wrapper
    return self.admin_view(view, cacheable)(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    if not self.has_permission(request):
  File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py", line 173, in has_permission
    return request.user.is_active and request.user.is_staff
AttributeError: 'WSGIRequest' object has no attribute 'user'
[21/Jun/2016 15:26:18] "GET /admin/ HTTP/1.1" 500 78473

Im quite new in django ... but I followed this tutorial: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/

我在 Django 中很新……但我遵循了本教程:https: //docs.djangoproject.com/en/1.9/ref/contrib/admin/

I dont have any custom AdminSites and custom AdminModels.

我没有任何自定义 AdminSites 和自定义 AdminModels。

I already googled about this problem but still I cannot solve it for my case in any way. Can you help ?

我已经用谷歌搜索过这个问题,但仍然无法以任何方式解决我的问题。你能帮我吗 ?

here is my settings.py:

这是我的settings.py

"""
Django settings for librato_chart_sender_web project.

Generated by 'django-admin startproject' using Django 1.11.dev20160523235928.

For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*1@+=wzrqx^6z&@2@d8r(w$js+ktw45lv2skez(=kz+rwff_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'librato_chart_sender',
    'fontawesome',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'librato_chart_sender_web.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'librato_chart_sender/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'librato_chart_sender_web.wsgi.application'


# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'GMT'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    ('css', 'librato_chart_sender/static/css'),
    ('js', 'librato_chart_sender/static/js'),
    ('fonts', 'librato_chart_sender/static/fonts'),
]

and admin.py:

admin.py

from django.contrib import admin
from .models import Configuration

# Register your models here.

admin.site.register(Configuration)

回答by Sir Mbuki

To resolve this go to settings.pywhere there is new-style MIDDLEWARE(introduced in Django 1.10)

要解决这个问题,请转到settings.py有新样式的地方MIDDLEWARE(在 Django 1.10 中引入)

Change that to old-style MIDDLEWARE_CLASSES

将其更改为旧样式 MIDDLEWARE_CLASSES

https://docs.djangoproject.com/en/stable/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware

https://docs.djangoproject.com/en/stable/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware

回答by Gon?alo Correia

I found the answer. The variable name on:

我找到了答案。变量名:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]

MIDDLEWAREis the new-style configuration introduced in Django 1.10. Change the name to MIDDLEWARE_CLASSESand now it works.

MIDDLEWARE是 Django 1.10 中引入的新式配置。将名称更改为MIDDLEWARE_CLASSES现在可以使用了。

So now the code is:

所以现在的代码是:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]

回答by kayoz

In case anyone is having this problem with Django 2.0, the following configuration with new-style MIDDLEWAREseems to work (docs here):

如果有人在 Django 2.0 中遇到此问题,以下具有新样式的配置MIDDLEWARE似乎有效(此处文档):

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]

回答by Chimaobi Emmanuel Ezeigbo

In case anyone is having the same problem in django 2.0.2 or later,

如果有人在 django 2.0.2 或更高版本中遇到同样的问题,

just update

刚更新

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickHymaning.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)

with

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]

It worked for me cause i created my project with django 1.0.x but later updated to django 2.0.2

它对我有用,因为我用 django 1.0.x 创建了我的项目,但后来更新到 django 2.0.2

回答by Jose Hidalgo

You should not change MIDDLEWARE to MIDDLEWARE_CLASSES. What happens here is more likely that you created the app with django 1.10 and now you are running it with 1.9 or a previous version.

您不应将 MIDDLEWARE 更改为 MIDDLEWARE_CLASSES。这里发生的情况更有可能是您使用 django 1.10 创建了应用程序,而现在您正在使用 1.9 或以前的版本运行它。

Make sure you use a specific version of django(and all other libraries) so your project doesn't break when deploying or running on different machines.

确保您使用特定版本的 django(和所有其他库),以便您的项目在不同机器上部署或运行​​时不会中断。

If you have a stable codebase simply run:

如果你有一个稳定的代码库,只需运行:

pip freeze > requirements.txt

And then when deploying or setting up a new env just do:

然后在部署或设置新环境时,只需执行以下操作:

pip install -r requirements.txt

You should always consider using fixed versions of your libraries(and hopefully virtual envs), and when upgrading dependencies test each version change.

您应该始终考虑使用库的固定版本(最好是虚拟环境),并且在升级依赖项时测试每个版本更改。

回答by Yura Liashenko

My solution was that my Django ver. was 1.9 I reinstalled back to 1.10 without changing MIDDLEWARE to MIDDLEWARE_CLASSES.

我的解决方案是我的 Django 版本。是 1.9 我重新安装回 1.10 而不将 MIDDLEWARE 更改为 MIDDLEWARE_CLASSES。

回答by brainLoop

Simple.....

简单的.....

If you have picked the code from somewhere else(mean project is not created on your pc)... then their may be a different configuration of MIDDLEWARE in setting file in your code.....so you need to just replace that MIDDLLEWARE from the one that your django produces( create a throwaway project->go to setting files ---> copy that MIDDLEWARE part and paste it in the project in which you are getting error).

如果您从其他地方选择了代码(意味着项目未在您的 PC 上创建)...那么它们可能是您代码中设置文件中不同的 MIDDLEWARE 配置.....所以您只需要替换该 MIDDLLEWARE从 django 生成的那个(创建一个一次性项目-> 转到设置文件 ---> 复制该 MIDDLEWARE 部分并将其粘贴到出现错误的项目中)。

回答by Madox

I had a similar error in my production server and thanks to sentry's breadcrumbs I saw that the error that was raising had to do with my settings, especially the ALLOWED_HOSTS.

我在我的生产服务器中遇到了类似的错误,多亏了哨兵的面包屑,我看到引发的错误与我的设置有关,尤其是 ALLOWED_HOSTS。

Django version 1.10.8 with python 2.7.

带有 python 2.7 的 Django 版本 1.10.8。

My previous settings:

我之前的设置:

ALLOWED_HOSTS = ['0.0.0.0',
                 'beta.mydomain.co.uk',
                 'mydomain.co.uk',
                 'www.mydomain.co.uk',
                 'alpha.mydomain.co.uk']

Sentry Breadcrumbs screen shot: sentry breadcrumb screenshot

哨兵面包屑屏幕截图: 哨兵面包屑截图

After that I looked around and found this:

之后我环顾四周,发现了这个:

A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com.

以句点开头的值可以用作子域通配符:“.example.com”将匹配 example.com、www.example.com 和 example.com 的任何其他子域。

Link to Django official docs

链接到Django 官方文档

So my final settings that solved my problem:

所以我的最终设置解决了我的问题:

ALLOWED_HOSTS = ['0.0.0.0',
                 'mydomain.co.uk',
                 'www.mydomain.co.uk',
                 '.mydomain.co.uk']

Hope this was useful :)

希望这是有用的:)