gpt4 book ai didi

python - 如何从 Wagtail CMS 中的 streamfield 检索页面内容?

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:19 25 4
gpt4 key购买 nike

我创建了 SolutionPage 并且在 It's content 字段中有嵌套的 short_portfolio block 。我通过 Wagtail 管理面板向 PageChooserBlock 添加了几个 ProjectPage 实例。

class SolutionPage(Page):
...
content = StreamField([
...
...
('short_portfolio', blocks.StructBlock([
('title', blocks.CharBlock(required=False)),
('description', blocks.RichTextBlock(required=True)),
('projects', blocks.StreamBlock([
('project', blocks.PageChooserBlock(ProjectPage)),
], required=False, max_num=4)),
])),
], blank=True, null=True, validators=[UniqueProjectsInShortPortfolioValidator()])

现在,我正在为 PDF 导出开发 API View 我需要从给定的 中提取所有 ProjectPage 对象解决方案页面

import requests
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import views
from rest_framework.generics import get_object_or_404

from portfolio.models import ProjectPage
from solutions.models import SolutionPage

class PortfolioToPdfView(views.APIView):
def get(self, request, *args, **kwargs):
def get_404():
return HttpResponse(
render(
request=None,
template_name='404.html',
content_type="text/html"
),
content_type='text/html'
)

path = request.META['PATH_INFO']
if path.find('solutions') == -1:
return get_404()
slug = path[path[1:].find('/') + 2:]
slug = slug[:slug.find('/')]

solution_page = get_object_or_404(SolutionPage, slug=slug)
short_portfolio = solution_page.content.stream_block.child_blocks["short_portfolio"]

projects = [project.child_blocks["project"].target_model for project in short_portfolio.child_blocks["projects"]]

...
response = HttpResponse(request, content_type='application/pdf')
return response

问题是,通过这种方式我只能提取页面的“架构”之类​​的东西,而不能提取实际内容。

TypeError at /solutions/ai-driven-machine-learning-software/portfolio-pdf/
'StreamBlock' object is not iterable

Debug variables

最佳答案

solution_page.content.stream_block.child_blocks["short_portfolio"] 将为您提供 short_portfolio block 的定义,而不是该 block 的特定实例。为此,您需要遍历字段内容,寻找匹配 block_type 的 block :

projects = []
for block in solution_page.content:
if block.block_type == 'short_portfolio':
for project_block in block.value['projects']:
projects.append(project_block.value)

关于python - 如何从 Wagtail CMS 中的 streamfield 检索页面内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55278333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com