Django 模板中的奇怪行为
Weird behavior in Django template
我在用户配置文件模板中有这一部分:
<p>{{ user.get_username }} = {{ profile.username }} </p>
{% if user.is_authenticated %}
{% if user.get_username != profile.username %}
This is the profile of another user
{% else%}
This is your profile
{% endif %}
{% endif %}
生成这个看似荒谬的输出:
bob = bob
This is the profile of another user
为什么会这样,如何解决?
更新:
这是 UserProfile 模型:
class UserProfile(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length=30, blank=True)
city = models.CharField(max_length=30, blank=True)
canpost=models.BooleanField(default=True)
User.profile = property(lambda u:UserProfile.objects.get_or_create(username=u)[0])
您的代码正在将用户 username
(字符串)与配置文件 username
(它是一个对象)进行比较。您可以使用 profile.username.username
而不是 profile.username
,但正确的约定(这也更符合逻辑)是将 Profile 模型的 username
字段重命名为 user
,并访问通过 profile.user.username
命名。
我在用户配置文件模板中有这一部分:
<p>{{ user.get_username }} = {{ profile.username }} </p>
{% if user.is_authenticated %}
{% if user.get_username != profile.username %}
This is the profile of another user
{% else%}
This is your profile
{% endif %}
{% endif %}
生成这个看似荒谬的输出:
bob = bob
This is the profile of another user
为什么会这样,如何解决?
更新: 这是 UserProfile 模型:
class UserProfile(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length=30, blank=True)
city = models.CharField(max_length=30, blank=True)
canpost=models.BooleanField(default=True)
User.profile = property(lambda u:UserProfile.objects.get_or_create(username=u)[0])
您的代码正在将用户 username
(字符串)与配置文件 username
(它是一个对象)进行比较。您可以使用 profile.username.username
而不是 profile.username
,但正确的约定(这也更符合逻辑)是将 Profile 模型的 username
字段重命名为 user
,并访问通过 profile.user.username
命名。