Django – 登录后的模板不知道用户是否已验证身份。

huangapple go评论59阅读模式
英文:

Django - after sign-in template don't know that user is authenticated

问题

views.pl

以下代码可能有效没有错误出现):

class SignInView(View):

    def get(self, request):
        return render(request, "signin.html")

    def post(self, request):
        user = request.POST.get('username', '')
        pass = request.POST.get('password', '')

        user = authenticate(username=user, password=pass)

        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse("Bad user.")
        else:
            return HttpResponseRedirect('/')

....但在模板中:

{% user.is_authenticated %}

不是真的。所以我看不到任何用于已认证用户的功能。

问题是什么?



<details>
<summary>英文:</summary>

Below code probably works (no errors present):

**views.pl**

class SignInView(View):

def get(self, request):
    return render(request, &quot;signin.html&quot;)

def post(self, request):
    user = request.POST.get(&#39;username&#39;, &#39;&#39;)
    pass = request.POST.get(&#39;password&#39;, &#39;&#39;)

    user = authenticate(username=user, password=pass)

    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(&#39;/&#39;)
        else:
            return HttpResponse(&quot;Bad user.&quot;)
    else:
        return HttpResponseRedirect(&#39;/&#39;)

....but in template:

{% user.is_authenticated %}


is not True. So I don&#39;t see any functionality for authenticated user.

What is the problem?


</details>


# 答案1
**得分**: 1

你应该像这样做:`{% if request.user.is_authenticated %}` 或 `{% if user.is_authenticated %}`。

<details>
<summary>英文:</summary>

You should do like `{% if request.user.is_authenticated %}` or `{% if user.is_authenticated %}`


</details>



# 答案2
**得分**: 1

你应该做类似以下的事情:

```html
{% if request.user.is_authenticated %}
    &lt;!-- 针对已验证用户的代码 --&gt;
{% else %}
    &lt;!-- 针对未验证用户的代码 --&gt;
{% endif %}

我在视图中还发现另一个问题,pass 是 Python 中的一个保留关键字,你也应该更改变量名称。

英文:

You should do something like:

{% if request.user.is_authenticated %}
    &lt;!-- code for authenticated user --&gt;
{% else %}
    &lt;!-- code for unauthenticated user --&gt;
{% endif %}

I could see another problem in views, pass is a reverse keyword in Python, you should also change variable name.

huangapple
  • 本文由 发表于 2023年2月14日 02:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定