【问题标题】:'is_authenticated' still always returns false in template'is_authenticated' 仍然总是在模板中返回 false
【发布时间】:2014-08-31 23:47:52
【问题描述】:

这是我的另一个 question 的后续,因为它可能需要不同的答案。

我模板中的代码总是返回 false:

   {% if request.user.is_authenticated %}
      <p>I'm logged in</p>
   {% else %}
      <p>I am anonymous</p>
   {% endif %}

我从文档中了解到,我需要在 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 中包含“django.contrib.auth.context_processors.auth”,所以我这样做如下:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.contrib.auth.context_processors.auth", #Added
)

至于我的views.py,我使用的是render_to_response(),但我觉得这可能是导致问题的原因。我还需要在上下文中从数据库中传递一个用户,但添加了第三个参数context_instance=RequestContext(request)

def public_profile(request, username_in_url):
    user = User.objects.get(username = username_in_url)
    context = {
        'user': user,       
    }

    return render_to_response('public_profile.html', context, context_instance=RequestContext(request))

为什么request.user.is_authenticated 仍然返回 false,即使用户已登录?在views.py 中使用相同的方法正确,例如

if request.user.is_authenticated():
        return render_to_response('public_profile.html', context)
    else:
        return render_to_response('public_profile_anon.html', context)

【问题讨论】:

  • 如果您在模板中使用 user.is_authenticated 是否有效?
  • 如果我把它改成 user.is_authenticated 那么它会产生相反的效果!它总是返回 true!

标签: django django-templates django-views


【解决方案1】:

django.contrib.auth.context_processors.authdocumentation 表示此上下文处理器定义了两个变量:userperms。而user

代表当前登录用户的auth.User 实例(或AnonymousUser 实例,如果客户端未登录)。

因此,尽管在您的 Python 代码中您将访问 request.user 来执行您的检查,但在模板中它是 user

您的具体情况的问题是您还传递了一个字典,该字典在username_in_url 的基础上定义了user。这与django.contrib.auth.context_processors.auth 定义的变量冲突。

所以:

  1. 更改字典(您将其命名为 context),使 user 具有不同的名称。 (并在您的模板中更改对它的引用。)

  2. 更改您的模板以检查{% if user.is_authenticated %}

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多