【问题标题】:Creating a DetailView of a profile with a queryset of posts created by that user使用该用户创建的帖子查询集创建个人资料的 DetailView
【发布时间】:2023-02-05 11:25:45
【问题描述】:

我正在创建一个类似 Twitter 的应用程序,我坚持创建一个 UserProfileView,它应该显示某个用户的个人资料,以及下面该用户发布的帖子列表。虽然我真的想不出办法为此创建一个正确的视图。
我正在尝试为此使用基于类的视图,我将从中继承的视图可能是 DetailView(用于配置文件模型)以及其中的一些内容,用于检索该用户发布的帖子的查询集 -

我的个人资料模型如下所示:

class Profile(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    display_name = models.CharField(max_length=32)
    profile_picture = models.ImageField(
        default='assets/default.jpg', upload_to='profile_pictures')
    slug = models.SlugField(max_length=150, default=user)

    def get_absolute_url(self):
        return reverse("profile", kwargs={"pk": self.pk})

帖子模型:

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateField(auto_now_add=True)
    content = models.TextField(max_length=280)
    image = models.FileField(upload_to='post_images/', blank=True, null=True)

    def __str__(self) -> str:
        return f'Post by {self.author} on {self.date_posted} - {self.content[0:21]}'
    
    def get_absolute_url(self):
        return reverse("post-detail", kwargs={"pk": self.pk}) 

我试过创建这个方法:

class UserProfileView(DetailView):

    model = Profile
    context_object_name = 'profile'
    template_name = 'users/profile.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_posts'] = Post.objects.filter(author=Profile.user)
        return context

但不幸的是,这个不起作用,引发了一个错误

"TypeError: Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardOneToOneDescriptor object at 0x000001A5ACE80250>."

如果我用 author=Profile.user.id 替换过滤器参数,则返回“ForwardOneToOneDescriptor”对象没有属性“id”

不确定是我过滤帖子的方式有问题,还是我使用get_context_data的方式有问题。
我已经坚持了很长时间了,我感到非常沮丧,请帮助我。

【问题讨论】:

    标签: python django-models django-views


    【解决方案1】:

    该对象存储为self.object,因此您可以使用以下方式进行过滤:

    class UserProfileView(DetailView):
    
        model = Profile
        context_object_name = 'profile'
        template_name = 'users/profile.html'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['user_posts'] = Post.objects.filter(author_id=self.object.user_id)
            return context

    笔记: 通常使用settings.AUTH_USER_MODEL [Django-doc] 来引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多