Django模板中的奇怪行为

时间:2015-09-08 01:23:31

标签: django django-templates

我在用户个人资料模板中有这个部分:

    <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])

1 个答案:

答案 0 :(得分:2)

您的代码正在将用户username(字符串)与配置文件username(对象)进行比较。您可以使用profile.username.username代替profile.username,但正确的约定(也更符合逻辑)是将您的个人资料模型的username字段重命名为user,并访问通过profile.user.username命名。