【问题标题】:Show all user articles from another view in profile [django]在配置文件 [django] 的另一个视图中显示所有用户文章
【发布时间】:2020-10-13 12:37:37
【问题描述】:

我在 news_app

中有文章模型
class Article(Created, HitCountMixin):
    title = models.CharField(max_length=120)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)  
    snippet = models.TextField(null=False)

有视图:

class AllArticlesListView(ListView):
    template_name = 'news/articles_list.html'
    model = Article
    paginate_by = 5

    def get_queryset(self):
        return self.model.objects.all().order_by('-pk')

在另一个应用程序(user_app)中,我有个人资料模型

class Profile(AbstractUser):
    bio = models.TextField(blank=True, null=True, default='Brak')

有视图

class ProfileView(HitCountDetailView):
    model = Profile
    template_name = 'profile/profile.html'

项目网址我有:

path("<slug:slug>", ProfileView.as_view(), name='profile'),

news_app url 我有:

path('all/', AllArticlesListView.as_view(), name='all_articles_list'),

如何在他的用户资料中显示所有用户文章?

class ProfileView(DetailView):
    model = Profile
    template_name = 'profile/profile.html'
    count_hit = True

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    将您的文章添加到上下文中;

        def get_context_data(self, **kwargs):
            """ Add the articles to the context """
            context = super().get_context_data(**kwargs)
            if self.request.user.is_authenticated:
                context['articles'] = Article.objects.filter(author=self.request.user)
            return context
    

    您可以在此处找到DetailView 和其他 django 视图的详细信息; http://ccbv.co.uk/projects/Django/3.0/django.views.generic.detail/DetailView/

    【讨论】:

    • 谢谢!我会检查的。有可能在上下文中制作超过 1 个模型?
    • 你可以添加任何你想要的东西。它只是返回一个内容字典,然后您的模板可以访问这些内容
    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 2010-12-21
    • 2014-12-24
    • 2015-08-10
    • 2019-11-10
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多