gpt4 book ai didi

Python Django 如何在views.py 中获取登录用户的值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:05 31 4
gpt4 key购买 nike

我有用于日志记录的 CustomUser 类,还有另一个类 coach,其中包含有关我的用户的信息。每个用户都链接到教练类(class)。我想创建一个模板,如果我的用户完成了他们的个人资料,他们将看到他们的信息,如果他们没有完成他们的个人资料,他们将看到一条消息。我正在学习 Python Django,但我不知道如何从类 coach 中获取已登录用户的 Adresse 并检查它是否为空。知道如何解决这个问题吗?

我的观点.py

def Profile(request):
u = request.user.username
x = u.coach.Adresse

if len(x)!= 0:
completed = "profile completed"
return render(request, 'Profile.html', {'completed': completed})
else:
notcompleted = "please complete your profile"
return render(request, 'Profile.html', {'notcompleted': notcompleted})

我的模型.py

class coach(models.Model):
user = models.OneToOneField(CustomUser,on_delete=models.CASCADE)
Adresse = models.TextField(max_length=140, default='DEFAULT VALUE')
Telephone = models.IntegerField(null=True, max_length=140, default='111')

最佳答案

您的请求会自动添加到模板中,这意味着您可以在模板中访问它,而无需在上下文中传递它。它通过 render 函数传递给模板。

因此,请在您的 Profile.html 模板中写入以下内容:

{% if request.user.is_authenticated %}
<p>
{% if request.user.coach.Adresse != 'DEFAULT VALUE' %}
Profile Completed
{% else %}
Please complete your profile
{% endif %}
</p>
{% endif %}

并将Profile方法更改为

def Profile(request):
return render(request, 'Profile.html')

但我认为您应该更改 Adresse 字段,因为我认为您没有理由使用默认值。只需删除默认值并允许其为空和 null,如下所示:

Adresse = models.TextField(max_length=140, blank=True, null=True)

在模板中,而不是 {% if request.user.coach.Adresse != 'DEFAULT VALUE' %} 写入 {% if request.user.coach.Adresse %}

关于Python Django 如何在views.py 中获取登录用户的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465730/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com