慕碼人8056858
2023-02-07 14:24:37
我想創(chuàng)建一個(gè) user_posts 視圖,其中包含與特定用戶相關(guān)的所有帖子讓我們說有/有用戶“Natsu”寫的博客帖子然后登錄用戶讓我們說“Testuser”將能夠看到所有帖子由該用戶即用戶“Natsu”的所有帖子。blog models.pyclass Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField()user models.pyclass Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pic', default='default.jpg') def __str__(self): return f'{ self.user.username } Profile'views.pydef user_posts(request, username): posts = Post.objects.filter(author=username) return render(request, 'blog/user_posts.html', {'posts':posts})user_posts.html{% for post in posts %} <a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a> <h2><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></h2> {{ post.body|truncatewords:30 }} {% endfor %}urls.py path('user/<str:username>/', views.user_posts, name='user-posts'),但是當(dāng)我訪問那個(gè) url 時(shí)它顯示錯(cuò)誤Field 'id' expected a number but got 'admin'.
3 回答

有只小跳蛙
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊
author
onPost
將是User
表的主鍵,它是一個(gè)整數(shù)(除非從默認(rèn)值修改)而不是username
. username
您要么需要首先查找,User
要么使用其他一些 Django“魔法”。也許嘗試其中之一(我認(rèn)為他們都在后端做同樣的事情):
posts = Post.objects.filter(author=User.object.filter(username=username)[:1])
或者
posts = Post.objects.filter(author__username=username)
(我也沒有測(cè)試......所以請(qǐng)隨意編輯這個(gè)答案或評(píng)論,如果兩者都不起作用)

翻閱古今
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
當(dāng)您為 auhor 字段使用外鍵時(shí),我認(rèn)為您不能通過 posts = Post.objects.filter(author=username)
. 你能試試filter(author=user.id)
嗎?

回首憶惘然
TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
posts = Post.objects.filter(author=User.object.get(username=username))
或者
posts = Post.objects.filter(author__username=username)
添加回答
舉報(bào)
0/150
提交
取消