簡體   English   中英

Django:無法將登錄用戶與帖子作者進行比較

[英]Django:Unable to compare the logged in user with the author of the post

我正在構建一個 django 博客網站。我想將當前登錄的用戶與博客文章的作者進行比較,如果它們相同,則允許他們使用編輯功能,但我的代碼沒有執行 if 語句,即使它們都是是一樣的。

{% 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

你不應該檢查username ,你應該檢查 user 對象本身。

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

您正在比較代碼中的User usernameUser實例。 將條件更新為如下所示:

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

或者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM