gpt4 book ai didi

python - 在 Django 中显示用户的所有帖子

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:47 25 4
gpt4 key购买 nike

我想获取用户发送的所有帖子。例如用户:admin,它会显示管理员的帖子。我写了一些代码,但可能我犯了一个错误,我得到了一个错误。我得到的错误:

AttributeError at /index_page/

'WSGIRequest' object has no attribute 'models'

这是我的代码:

views.py

def index_page(request):
logged_in_user = request.models.author
logged_in_user_posts = Post.objects.filter(author=user)

return render(request, 'blog/post_list.html', {'posts': logged_in_user_posts})

模型.py

class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = RichTextField()
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

post_list.html

<div>
{% for post in posts %}

Username: {{ post.author.username }}
Post: {{ post.text }}

<br>

{% endfor %}

我的错误在哪里?

最佳答案

错误已经提示到该行:

    logged_in_user = <b>request.models.author</b>

request 对象没有 models 属性。它有一个指定登录用户的 .user 属性,因此您可以使用:

    logged_in_user = <b>request.user</b>

还有一个错误:你使用了Post.objects.filter(user=user),但是也没有user变量,有一个logged_in_user 变量。所以你可以修复 View :

def index_page(request):
logged_in_user_posts = Post.objects.filter(author=<b>request.user</b>)
return render(request, 'blog/post_list.html', {'posts': logged_in_user_posts})

额外说明:

  1. 因为你需要一个用户,所以用 login_required decorator [Django-doc] 修饰函数是有意义的;和
  2. 由于 Django 允许您更改 User 模型,因此使用 standard way to refer to the user model [Django-doc] 可能会有所帮助.如果您稍后改变主意并实现另一个用户模型,创建迁移将自动让关系引用新模型。

上面的两条评论严格不是让它工作所必需的。但我认为这是开发 Django 应用程序时的良好做法(当然这些可能有点“基于意见”)。

关于python - 在 Django 中显示用户的所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com