在本文中,我们将给您介绍关于Django中request.user指的是什么?的详细内容,并且为您解答djangopermission_required的相关问题,此外,我们还将为您提供关于'WSGI
在本文中,我们将给您介绍关于Django中request.user指的是什么?的详细内容,并且为您解答django permission_required的相关问题,此外,我们还将为您提供关于'WSGIRequest'对象没有属性'user'Django admin、angularjs – Django Rest Framework – Request.user始终是AnonymousUser,request.POST为空、django - request.POST和request.body获取值时出现的情况、django form – 将request.user传递给widget呈现函数的知识。
本文目录一览:- Django中request.user指的是什么?(django permission_required)
- 'WSGIRequest'对象没有属性'user'Django admin
- angularjs – Django Rest Framework – Request.user始终是AnonymousUser,request.POST为空
- django - request.POST和request.body获取值时出现的情况
- django form – 将request.user传递给widget呈现函数
Django中request.user指的是什么?(django permission_required)
我对 request.user 在Django中指的是什么感到困惑?它是指 auth_user 表中的 用户 名字
段,还是指用户模型实例?
我有这个疑问,因为我无法使用{{request.user.username}}
或访问模板中的电子邮件字段{{user.username}}
。
因此,我改为在views文件中执行以下操作:
userr = User.objects.get(username=request.user)
并传递userr
给模板,并以访问电子邮件字段{{ userr.email }}
。
尽管它可以正常工作,但我想对此有所了解。
答案1
小编典典如果您的模板正在接收AnonymousUser,{{request.user.email}}
将找不到对它的引用。以前,您必须询问是否{{request.user.is_authenticated}}
。
您必须检查设置部分是否包含django.core.context_processors.auth
上下文处理器TEMPLATE_CONTEXT_PROCESSORS
。如果您使用的是Django
1.4或最新版本,则上下文处理器为django.contrib.auth.context_processors.auth
。该上下文处理器负责在每个请求中包括用户对象。
'WSGIRequest'对象没有属性'user'Django admin
当我尝试访问管理页面时,出现以下错误:
System check identified no issues (0 silenced).June 21, 2016 - 15:26:14Django 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_staffAttributeError: ''WSGIRequest'' object has no attribute ''user''[21/Jun/2016 15:26:18] "GET /admin/ HTTP/1.1" 500 78473
我是django的新手,但我遵循了本教程:https : //docs.djangoproject.com/en/1.9/ref/contrib/admin/
我没有任何自定义AdminSite和自定义AdminModel。
我已经用谷歌搜索了这个问题,但仍然无法以任何方式解决我的问题。你能帮我吗 ?
这是我的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, seehttps://docs.djangoproject.com/en/dev/topics/settings/For the full list of settings and their values, seehttps://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^6$9z&@2@d8r(w$js+ktw45lv2skez(=kz+rwff_''# SECURITY WARNING: don''t run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_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.clickjacking.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/#databasesDATABASES = { ''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-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_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''),]
和admin.py:
from django.contrib import adminfrom .models import Configuration# Register your models here.admin.site.register(Configuration)
答案1
小编典典要解决此问题,请转到settings.py
存在新样式的地方MIDDLEWARE
(在Django 1.10中引入)
将其更改为旧样式 MIDDLEWARE_CLASSES
答案2
小编典典我找到了答案。变量名称在:
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.clickjacking.XFrameOptionsMiddleware'',]
MIDDLEWARE
是Django 1.10中引入的新型配置。将名称更改为MIDDLEWARE_CLASSES
,现在可以使用了。
所以现在的代码是:
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.clickjacking.XFrameOptionsMiddleware'',]
angularjs – Django Rest Framework – Request.user始终是AnonymousUser,request.POST为空
尝试通过身份验证视图登录时,request.user始终是AnonymousUser,就像我没有提供任何身份验证凭据一样.我已经尝试记录request.POST但它似乎是一个空的dict.
我在这里有一个追溯:
Environment: Request Method: POST Request URL: http://45.55.149.3:8000/api/auth/ Django Version: 1.8.3 Python Version: 2.7.6 Installed Applications: ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','webapp','rest_framework','djrill') Installed Middleware: ('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.clickjacking.XFrameOptionsMiddleware','django.middleware.security.SecurityMiddleware') Traceback: File "/home/appointments-app/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request,*callback_args,**callback_kwargs) File "/home/appointments-app/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args,**kwargs) File "/home/appointments-app/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request,*args,**kwargs) File "/home/appointments-app/venv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 456. response = self.handle_exception(exc) File "/home/appointments-app/venv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 453. response = handler(request,**kwargs) File "/home/appointments-app/appointments/webapp/views.py" in post 40. login(request,request.user) File "/home/appointments-app/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login 111. request.session[SESSION_KEY] = user._Meta.pk.value_to_string(user) Exception Type: AttributeError at /api/auth/ Exception Value: 'AnonymousUser' object has no attribute '_Meta'
这里我有API auth视图失败:
class AuthView(APIView): authentication_classes = (QuietBasicAuthentication,) def post(self,request,**kwargs): login(request,request.user) return Response(OldUserSerializer(request.user).data) def delete(self,**kwargs): logout(request) return Response({})
下面是我正在使用的身份验证类:
from rest_framework.authentication import BasicAuthentication class QuietBasicAuthentication(BasicAuthentication): # disclaimer: once the user is logged in,this should NOT be used as a # substitute for SessionAuthentication,which uses the django session cookie,# rather it can check credentials before a session cookie has been granted. def authenticate_header(self,request): return 'xBasic realm="%s"' % self.www_authenticate_realm
解决方法
现在通过调用login,您正在尝试登录当前用户(request.user)并将它们与当前请求(请求)相关联. DRF将自动为您执行此操作,request.user将包含一个User实例,如果它能够验证用户和AnonymousUser(您看到的),如果它不能.
如果您尝试登录用户以获取Django请求(而不是DRF请求,which is different),则需要引用存储为request._request的Django请求.
login(request._request,request.user)
django - request.POST和request.body获取值时出现的情况
django request.POST / request.body
当request.POST没有值 需要考虑下面两个要求
1.如果请求头中的: Content-Type: application/x-www-form-urlencoded request.POST中才会有值(才会去request.body中解析数据)
2.若1有,也不一定有值 必须有数据格式要求: name=alex&age=18&gender=男
如:
a. form表单提交 默认就会满足上诉的1和2
<form method...>
input
</form>
b. ajax提交
$.ajax({
url:...
type:POST,
data:{
name:alex,
age=18,
} #默认也会满足上诉1和2 请求头默认为上述情况 内部数据格式会转为上述情况
})
自定义ajax 情况一
$.ajax({
url:...
type:POST,
headers:{''Content-Type'':"application/json"} #不同的请求头 导致request.POST获取不了数据 而request.body依旧存在数据
data:{name:alex, age = 18} #内部自动转换 name=alex&age=18
}) #即body有值 POST无值
自定义ajax 情况二
$.ajax({
url:...
type:POST,
headers:{''Content-Type'':"application/json"} #不同的请求头 导致request.POST获取不了数据 而request.body依旧存在数据
data:JSON.stringfy{name:alex, age = 18} #{name:alex,age:18}
}) #body有值 POST无值
#从 request.body里获取数据 然后再通过json.loads(request.body)
博客搬运地址
- django request.POST和request.body获取值时出现的情况
django form – 将request.user传递给widget呈现函数
解决方法
>覆盖表单上的init:
def __init__(self,*args,**kwargs): user = kwargs.pop('user',None) super(SomeForm,self).__init__(*args,**kwargs) self.fields['your_field'].widget.user = user
>覆盖您的小部件:
def __init__(self,**kwargs): self.user = None super(YourWidget,**kwargs)
>在小部件上与您的用户一起获利.
显然,您需要向表单提供用户,并且在某些边缘情况下这可能是一个问题,例如您正在使用django动态视图而您不愿意将它们更改为更静态的方法.
关于Django中request.user指的是什么?和django permission_required的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于'WSGIRequest'对象没有属性'user'Django admin、angularjs – Django Rest Framework – Request.user始终是AnonymousUser,request.POST为空、django - request.POST和request.body获取值时出现的情况、django form – 将request.user传递给widget呈现函数等相关知识的信息别忘了在本站进行查找喔。
本文标签: