2017-05-09 3 views
1

私はdjangoブログのウェブサイトを構築しています。現在ログインしているユーザーとブログ投稿の投稿者を比較したい場合は、それらに編集機能を許可しますが、私のコードは両方が同じであってもif文を実行しません。Django:ログインしたユーザーを投稿者と比較できません

{% if user.is_authenticated and user.username == post.author %} 

モデル -

class Post(models.Model): 
    author = models.ForeignKey('auth.User') 
    title = models.CharField(max_length=200) 
    text = models.TextField() 
    created_date = models.DateTimeField(
     default=timezone.now) 
    published_date = models.DateTimeField(
     blank=True, null=True) 

    def publish(self): 
    self.published_date = timezone.now() 
    self.save() 

    def __str__(self): 
    return self.title 
+0

あなたは 'post.author'を印刷できますか? –

+0

はい、post.authorを印刷できます – Bing

答えて

3

、ユーザー・オブジェクト自体に対してチェックする必要があります。

{% if user.is_authenticated and user == post.author %} 
1

あなたはあなたのコード内でusernameUserインスタンスを比較しています。このような何かに条件を更新します。あなたはusernameに対してチェックするべきではありません

{% if user.is_authenticated and user == post.author %}

または

{% if user.is_authenticated and user.username == post.author.username %}

関連する問題