如何修复“AnonymousUser”对象没有属性“配置文件”错误?

Posted

技术标签:

【中文标题】如何修复“AnonymousUser”对象没有属性“配置文件”错误?【英文标题】:how to fix the 'AnonymousUser' object has no attribute 'profile' error? 【发布时间】:2014-06-03 04:10:22 【问题描述】:

我正在为一个假设的社交网络编写一个聊天应用程序,但是当我尝试打开聊天页面时,我给出了以下错误 'AnonymousUser' object has no attribute 'profile' error 。 我认为模型文件中可能存在问题,但我真的不知道如何解决它,我现在真的很困惑!?谁能给点建议??

部分聊天views.py

def index(request):
if request.method == 'POST':
    print request.POST
    request.user.profile.is_chat_user=True
logged_users = []

if request.user.username and request.user.profile.is_chat_user:
    context = 'logged_users':logged_users
    cu = request.user.profile
    cu.is_chat_user = True
    cu.last_accessed = utcnow()
    cu.save()

    return render(request, 'djangoChat/index.html', context)

    try:
            eml = request.COOKIES[ 'email' ]
            pwd = request.COOKIES[ 'password' ]
    except KeyError:
            d = 'server_message':"You are not logged in."
            query_str = urlencode(d)

            return HttpResponseRedirect('/login/?'+query_str)

    try:
                    client = Vertex.objects.get(email = eml)
                    context = 'logged_users':logged_users
                    cu = request.user.profile
                    cu.is_chat_user = True
                    cu.last_accessed = utcnow()
                    cu.save()
                    if client.password != pwd:
                            raise LookupError()
    except Vertex.DoesNotExist:
                    sleep(3)
                    d = 'server_message':"Wrong username or password."
                    query_str = urlencode(d)
                    return HttpResponseRedirect('/login/?'+query_str)

    return render_to_response('djangoChat/index.html',
"USER_EMAIL":eml,request.user.profile.is_chat_user:True,
context_instance=RequestContext(request))



 @csrf_exempt
def chat_api(request):
if request.method == 'POST':
    d = json.loads(request.body)
    msg =  d.get('msg')
    user = request.user.username 
    gravatar = request.user.profile.gravatar_url
    m = Message(user=user,message=msg,gravatar=gravatar)
    m.save()


    res = 'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar
    data = json.dumps(res)
    return HttpResponse(data,content_type="application/json")


# get request
r = Message.objects.order_by('-time')[:70]
res = []
for msgs in reversed(r) :
    res.append('id':msgs.id,'user':msgs.user,'msg':msgs.message,'time':msgs.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':msgs.gravatar)

data = json.dumps(res)


return HttpResponse(data,content_type="application/json")

def logged_chat_users(request):

u = Vertex.objects.filter(is_chat_user=True)

for j in u:
    elapsed = utcnow() - j.last_accessed
    if elapsed > datetime.timedelta(seconds=35):

        j.is_chat_user = False
        j.save()

uu = Vertex.objects.filter(is_chat_user=True)


d = []
for i in uu:
    d.append('username': i.username,'gravatar':i.gravatar_url,'id':i.userID)
data = json.dumps(d)


return HttpResponse(data,content_type="application/json")

以及我的部分聊天模型:

class Message(models.Model):
user = models.CharField(max_length=200)

message = models.TextField(max_length=200)
time = models.DateTimeField(auto_now_add=True)
gravatar = models.CharField(max_length=300)
def __unicode__(self):
    return self.user
def save(self):
    if self.time == None:
        self.time = datetime.now()
    super(Message, self).save()




def generate_avatar(email):
           a = "http://www.gravatar.com/avatar/"
           a+=hashlib.md5(email.lower()).hexdigest()
           a+='?d=identicon'
           return a
def hash_username(username):
           a = binascii.crc32(username)
           return a
 # the problem seems to be here ??!
 User.profile = property(lambda u: Vertex.objects.get_or_create(user=u,defaults='gravatar_url':generate_avatar(u.email),'username':u.username,'userID':hash_username(u.username))[0])

最后是另一个应用程序的一部分(聊天用户):

class Vertex(models.Model,object):
user = models.OneToOneField(User)
password = models.CharField(max_length=50)
#user_id = models.CharField(max_length=100)

username = models.CharField(max_length=300)
userID =models.IntegerField()

Message = models.CharField(max_length=500)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.EmailField(max_length=75)
is_chat_user = models.BooleanField(default=False)
gravatar_url = models.CharField(max_length=300,null=True, blank=True)
last_accessed = models.DateTimeField(auto_now_add=True)

【问题讨论】:

【参考方案1】:

因为该用户尚未登录。 Django 将它们视为 AnonymousUser 并且 AnonymousUser 没有 profile 属性。

如果视图仅用于登录用户,您可以将login_required 装饰器添加到视图函数以强制登录过程。否则需要通过is_authenticated函数判断用户是否匿名。

参考:Using the Django authentication system

【讨论】:

如果该视图仅需要经过身份验证的用户访问,您的建议是有效的,但是我如何才能制作该视图,让匿名用户访问,同时向她询问个人资料财产? 使用上面文档中概述的“如果用户不是无:”来查看视图。在模板中使用 % if request.user %。

以上是关于如何修复“AnonymousUser”对象没有属性“配置文件”错误?的主要内容,如果未能解决你的问题,请参考以下文章

Django登录AttributeError:'AnonymousUser'对象没有属性'_meta'

'AnonymousUser'对象在Django登录功能中没有属性'_meta'错误

如何修复 AttributeError:“系列”对象没有“查找”属性?

如何修复此错误:“SQLContext 对象没有属性‘jsonFile’

如何修复python2.7中的“AttributeError:'module'对象没有属性'storage'”错误

如何修复此 AttributeError:“SubRequest”对象没有属性“getfuncargvalue”?