'WSGIRequest'对象没有属性'username'这是我得到的错误.我已经完成了与之相关的大部分问题,并做了相应的更改.但是还没有遇到解决方案.在我的settings.py中就是这样
TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.debug", "django.core.context_processors.i18n")
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
AUTH_PROFILE_MODULE = "prof.userprofile"
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
)
Run Code Online (Sandbox Code Playgroud)
我想知道这个错误意味着什么,因为这是我第一次遇到这样的错误.以及如何调试它?编辑:
Exception Value:
'WSGIRequest' object has no attribute 'username'
Exception Location: /home/satyajit/geodjango/geographic_admin/prof/views.py in view_foo, line 18
Run Code Online (Sandbox Code Playgroud)
这是我的views.py
from django.shortcuts import render_to_response
from django.contrib.gis.shortcuts import render_to_kml
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
@login_required
def view_foo(request):
user1 = User.objects.get(user=request.User.username)
return render_to_response('welcome.html', {})
Run Code Online (Sandbox Code Playgroud)
编辑:好吧我刚刚意识到这个查询有多愚蠢和我的错误:D.
如果你想要用户名,你可以这样做:
user1= request.user.username
Run Code Online (Sandbox Code Playgroud)
你得到了用户实例request.user.
this_user = request.user
Run Code Online (Sandbox Code Playgroud)
一点解释:您的初始查询没有多大意义,因为User类没有字段用户.此外,此查询是多余的,因为请求已提供用户实例(request.user,其是会话的用户)
python中的错误(及其回溯)几乎总是有用的,很少包含无关信息.
'WSGIRequest' object has no attribute 'username'. WSGIRequest是来自Web服务器的WSGI请求的请求类.约定是在视图中处理这些作为"请求"参数.所以错误表明你在request.bad_attribute某处,bad_attribute在这种情况下username.
您的请求只有一个属性,username如果某些中间件是活动的,则添加它.但是,django中的默认值包括添加user对象的中间件,因此这可能是您真正想要的. request.user.username.
此外,请记住,属性访问区分大小写.毕竟,它只是简单的Python.