英文:
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, "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('/')
....but in template:
{% user.is_authenticated %}
is not True. So I don'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 %}
<!-- 针对已验证用户的代码 -->
{% else %}
<!-- 针对未验证用户的代码 -->
{% endif %}
我在视图中还发现另一个问题,pass
是 Python 中的一个保留关键字,你也应该更改变量名称。
英文:
You should do something like:
{% if request.user.is_authenticated %}
<!-- code for authenticated user -->
{% else %}
<!-- code for unauthenticated user -->
{% endif %}
I could see another problem in views, pass
is a reverse keyword in Python, you should also change variable name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论