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

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

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

问题

views.pl

  1. 以下代码可能有效没有错误出现):
  2. class SignInView(View):
  3. def get(self, request):
  4. return render(request, "signin.html")
  5. def post(self, request):
  6. user = request.POST.get('username', '')
  7. pass = request.POST.get('password', '')
  8. user = authenticate(username=user, password=pass)
  9. if user is not None:
  10. if user.is_active:
  11. login(request, user)
  12. return HttpResponseRedirect('/')
  13. else:
  14. return HttpResponse("Bad user.")
  15. else:
  16. return HttpResponseRedirect('/')

....但在模板中:

  1. {% user.is_authenticated %}

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

问题是什么?

  1. <details>
  2. <summary>英文:</summary>
  3. Below code probably works (no errors present):
  4. **views.pl**

class SignInView(View):

  1. def get(self, request):
  2. return render(request, &quot;signin.html&quot;)
  3. def post(self, request):
  4. user = request.POST.get(&#39;username&#39;, &#39;&#39;)
  5. pass = request.POST.get(&#39;password&#39;, &#39;&#39;)
  6. user = authenticate(username=user, password=pass)
  7. if user is not None:
  8. if user.is_active:
  9. login(request, user)
  10. return HttpResponseRedirect(&#39;/&#39;)
  11. else:
  12. return HttpResponse(&quot;Bad user.&quot;)
  13. else:
  14. return HttpResponseRedirect(&#39;/&#39;)
  1. ....but in template:

{% user.is_authenticated %}

  1. is not True. So I don&#39;t see any functionality for authenticated user.
  2. What is the problem?
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 你应该像这样做:`{% if request.user.is_authenticated %}` `{% if user.is_authenticated %}`
  7. <details>
  8. <summary>英文:</summary>
  9. You should do like `{% if request.user.is_authenticated %}` or `{% if user.is_authenticated %}`
  10. </details>
  11. # 答案2
  12. **得分**: 1
  13. 你应该做类似以下的事情:
  14. ```html
  15. {% if request.user.is_authenticated %}
  16. &lt;!-- 针对已验证用户的代码 --&gt;
  17. {% else %}
  18. &lt;!-- 针对未验证用户的代码 --&gt;
  19. {% endif %}

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

英文:

You should do something like:

  1. {% if request.user.is_authenticated %}
  2. &lt;!-- code for authenticated user --&gt;
  3. {% else %}
  4. &lt;!-- code for unauthenticated user --&gt;
  5. {% 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:

确定