我对任何错误深表歉意,英语不是我的母语.

我正在制作多个组织的新闻和事件的网站(每个组织都有自己的帐户,允许他们自己创建新闻和事件).

以新闻为例:

NewsIndexPage是所有NewsArticlePage的父项. 每个NewsArticlePage都与组织联系在一起.

在URL/news/,NewsIndexPage显示所有新闻,并允许利用RoutablePageMixin(/news/organization/<str: organization_slug>/)按组织过滤新闻.

此外,每个组织都有自己的登录页(OrganizationPage),其中包含组织的信息和新闻部分. 新闻部分最多显示3条组织的最新新闻(如在bakerydemo个存储库中,当最新的3个博客条目在HomePage中列出时:

OrganizationPage个引用NewsIndexPageForeignKey.

但我不知道,当它通过ForeignKey访问时,如何过滤NewsIndexPage岁的子元素.

当我访问OrganizationPage个实例时,我希望将组织的插件传递给链接的NewsIndexPage,这样我就可以筛选子NewsArticlesPage.

我想出的唯一方法是创建模板标记,它将把slug作为参数传递给某种get_news_articles(self, organization_slug)函数.但我还没能做到这一点.

一百:

class NewsArticlePage(Page):
    """
    A news article page.
    """
    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text=_("Landscape mode only; horizontal width between 1000px and 3000px."),
    )
    body = StreamField(
        BaseStreamBlock(), verbose_name=_("News article page body"), blank=True, use_json_field=True
    )
    date_published = models.DateField(_("Date article published"), blank=True, null=True)
    organization = models.ForeignKey(
        to = Organization,
        on_delete = models.SET_NULL,
        related_name = "news_articles",
        blank=True,
        null=True,
    )

    content_panels = Page.content_panels + [
        FieldPanel("introduction"),
        FieldPanel("image"),
        FieldPanel("body"),
        FieldPanel("date_published"),
    ]
    private_panels = [
        FieldPanel("organization"),
    ]

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading=_("Details")),
        ObjectList(private_panels, heading=_("Admin only"), permission="superuser"),
    ])

    search_fields = Page.search_fields + [
        index.SearchField("body"),
    ]

    # Specifies parent to NewsArticlePage as being NewsIndexPages
    parent_page_types = ["NewsIndexPage"]

    # Specifies what content types can exist as children of NewsArticlePage.
    # Empty list means that no child content types are allowed.
    subpage_types = []

    base_form_class = NewsArticlePageForm

    class Meta:
        verbose_name = _("News article page")
        verbose_name_plural = _("News article pages")


class NewsIndexPage(RoutablePageMixin, Page):
    """
    Index page for news.
    """

    introduction = models.TextField(help_text=_("Text to describe the page"), blank=True)

    content_panels = Page.content_panels + [
        FieldPanel("introduction"),
    ]

    def get_context(self, request):
        context = super(NewsIndexPage, self).get_context(request)
        context["news_articles"] = (
            NewsArticlePage.objects.live().order_by("-date_published")
        )
        return context

    def children(self):
        return self.get_children().specific().live()
    
    @route(r"^organization/$", name="news_of_organization")
    @path("organization/<str:organization_slug>/", name="news_of_organization")
    def news_of_organization(self, request, organization_slug=None):
        """
        View function for the organization's news page
        """
        try:
            organization = Organization.objects.get(slug=organization_slug)
        except Organization.DoesNotExist:
            if organization:
                msg = "There are no news articles from organization {}".format(organization.get_shorten_name())
                messages.add_message(request, messages.INFO, msg)
            return redirect(self.url)
        
        news_articles = NewsArticlePage.objects.live().filter(organization__slug=organization_slug).order_by("-date_published")

        return self.render(request, context_overrides={
            'title': _("News"),
            'news_articles': news_articles,
        })


    def serve_preview(self, request, mode_name):
        # Needed for previews to work
        return self.serve(request)
    

    subpage_types = ["NewsArticlePage"]


    class Meta:
        verbose_name = _("News index page")
        verbose_name_plural = _("News index pages")

一百:

class Organization(index.Indexed, models.Model):
    # ...
    name = models.CharField(max_length=255)
    # ...
    slug = models.SlugField(
        verbose_name=_("Slug Name"),
        max_length=255,
        unique=True,
        blank=True,
        null=False,
    )
    # ...


class OrganizationPage(Page):
    """
    An organization page.
    """
    organization = models.OneToOneField(
        to=Organization,
        on_delete=models.SET_NULL,
        related_name="organization_page",
        verbose_name=_("Organization"),
        null=True,
        blank=True,
    )

    # Featured sections on the HomePage
    # News section
    news_section_title = models.CharField(
        blank=True, max_length=255, help_text=_("Title to display")
    )
    news_section = models.ForeignKey(
        "news.NewsIndexPage",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text=_(
            "News section. Will display up to three latest news articles."
        ),
        verbose_name=_("News section"),
    )

    content_panels = Page.content_panels + [
        MultiFieldPanel(
            [
                FieldPanel("news_section_title"),
                FieldPanel("news_section"),
            ],
            heading=_("News section"),
        ),
    ]

    private_panels = [
        FieldPanel("organization"),
    ]

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading=_("Details")),
        ObjectList(Page.promote_panels, heading=_("Promote")),
        ObjectList(private_panels, heading=_("Admin only"), permission="superuser"),
    ])

    # Specifies parent to OrganizationPage as being OrganizationsIndexPage
    parent_page_types = ["OrganizationsIndexPage"]

    # Specifies what content types can exist as children of OrganizationPage.
    # subpage_types = ["news.NewsIndexPage"]
    subpage_types = []

    class Meta:
        verbose_name = _("Organization page")
        verbose_name_plural = _("Organization pages")

templates/organizations/organizations/organization_page.html:

<!-- ... -->
<div class="container">
        <div class="row">
            <div class="news-articles-list">
                {% if page.news_section %}
                    <h2 class="featured-cards__title">{{ page.news_section_title }}</h2>
                    <div class="row">
                        {% for news_article in page.news_section.children|slice:"3" %}
                            {% include "includes/card/news-listing-card.html" with news_article=news_article %}
                        {% endfor %}
                    </div>
                    <a class="featured-cards__link" href="/news/organization/{{ page.slug }}">
                        <span>View more of our news</span>
                    </a>      
                {% endif %}
            </div>
        </div>
    </div>
<!-- ... -->

如有任何帮助和提示,我将不胜感激!

推荐答案

不要试图过滤模板中的查询--做到in a get_context method on the page model:

class OrganizationPage(Page):
    # ...
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['news_articles'] = NewsArticlePage.objects.child_of(self.news_section).filter(organization=self.organization).live()[:3]
        return context

这将使模板上的变量news_articles可用,您可以循环遍历该变量:

{% for news_article in news_articles %}
    {% include "includes/card/news-listing-card.html" with news_article=news_article %}
{% endfor %}

Python相关问答推荐

在函数内部使用eval(),将函数的输入作为字符串的一部分

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

在内部列表上滚动窗口

沿着数组中的轴计算真实条目

基于索引值的Pandas DataFrame条件填充

我对我应该做什么以及我如何做感到困惑'

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

在Python中计算连续天数

导入错误:无法导入名称';操作';

基于Scipy插值法的三次样条系数

基于多个数组的多个条件将值添加到numpy数组

计算空值

如何按row_id/row_number过滤数据帧

如何在一组行中找到循环?

提取数组每行的非零元素

在Django中重命名我的表后,旧表中的项目不会被移动或删除

PySpark:如何最有效地读取不同列位置的多个CSV文件

Django在一个不是ForeignKey的字段上加入'

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

try 使用RegEx解析由标识多行文本数据的3行头组成的日志(log)文件