子类化列表视图以将多个视图引用到一个模板django

subclassing listview for referencing multiple views to one template django

假设在一个网站中有一个用户个人资料页面,它是一个博客网站。所以每个用户都有一些他们写的博客。所以我希望个人资料页面是这样的:它将显示有关该用户的详细信息,如用户名、电子邮件。他们写的所有博客也应该列在那里。现在我这里有两个视图,一个是详细的个人资料,另一个是列出用户写的博客。

#view for detailed profile stuffs
class ProfileDetailView(DetailView):
    model = User

#view for listing blogs written by user
class UserPostListView(ListView):
    model = Post 
    paginate_by = 5

还有Post模型是这样的:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

现在您可以看到一个视图继承自 ListView,另一个视图继承自 DetailView。 为了使用这两个视图来呈现我想要的内容,我不能将两个视图传递给一个模板。所以我需要子类化 them.Now 之一,因为我想保持分页,我应该子类化 UserPostListView 并且可能重写 get_context_data()。那我该怎么做呢?我找不到满意的答案。我也是 django 的新手。

任何帮助将不胜感激。

您需要先更新 Post 模型 - 为用户添加一个外键字段,以便知道哪个用户发布了什么。接下来覆盖 ProfileDetailView 中的 get_context_data() 函数,并传递用户在上下文中编写的所有帖子。 您的 get_context_data() cal 看起来像-

def get_context_data(self, **kwargs):
    context = super(ProfileDetailView, self).get_context_data(**kwargs)
    user = self.get_object()
    posts = Post.objects.filter(user=user)
    context.update({'posts': posts})
    return context

然后您可以通过-

在模板上呈现每个配置文件的帖子
{% for post in posts %}
    {{ post.title }}
    {{ post.comment }}
{% endfor %}

我可以通过像这样子类化 ListView 来做到这一点:

class UserPostListView(ListView):
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        self.usr = get_object_or_404(User, pk=self.kwargs['pk'])
        context['prof'] = self.usr.profile
        return context

    def get_queryset(self):
        return Post.objects.filter(author=self.usr)