【问题标题】:django get_profile errordjango get_profile 错误
【发布时间】:2012-07-16 09:50:48
【问题描述】:

我想在我已经包含在 settings.py 下面的视图中获取我的用户配置文件 ID

 AUTH_PROFILE_MODULE = 'users.UserProfile'

查看代码:

def savecontent(request):
 try:
  logging.debug("=========================== in save content")
  logging.debug(dir(request.user))
  my_id = request.user.get_profile().id
  logging.debug(my_id)

错误是:

 2012-07-17 13:00:00,564 ERROR Error while saing content
 Traceback (most recent call last):
 File "/opt/labs/labs_site/content/views.py", line 21, in savecontent
 my_id = request.user.get_profile().id
 File "/opt/labs/django/django/utils/functional.py", line 185, in inner
 return func(self._wrapped, *args)
 AttributeError: 'AnonymousUser' object has no attribute 'get_profile'

【问题讨论】:

    标签: django django-models django-templates django-views


    【解决方案1】:
    AttributeError: 'AnonymousUser' object has no attribute 'get_profile'
    

    您必须拥有经过身份验证的用户才能检索个人资料,这是您的问题

    @login_required
    def foo(request):
        profile_id = request.user.get_profile().id
    

    【讨论】:

    • no - 他的意思是 HTTP 请求必须由已经过身份验证的用户发出。您的错误输出显示用户是“AnonymousUser”,这是 Django 在用户未通过身份验证时使用的。
    • if request.user.is_authenticated(): 本身没有通过
    • 对不起 - 这没有意义。你的意思是request.user.is_authenticated() == False?如果是这样,那就是您的问题 - 您需要登录。
    • tbh 你不应该尝试检索这样的个人资料,我已经编辑了我的答案以获得更好的例程
    • 其实 login_required 会保证你有经过身份验证的用户我简单你的看法,所以不需要检查它是否存在。
    猜你喜欢
    • 2014-01-03
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2011-10-02
    • 2015-06-15
    • 2015-10-24
    相关资源
    最近更新 更多