从个人资料[django]

时间:2020-10-13 12:37:37

标签: django django-views django-templates

我在 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网址中,我有:

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

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

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

1 个答案:

答案 0 :(得分:0)

将文章添加到上下文中

    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/