我已经创建了SolutionPage
,并且在content
字段中嵌套了short_portfolio
块。我已通过Wagtail管理面板将多个ProjectPage
实例添加到PageChooserBlock
。
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()])
现在,我正在使用 API视图进行PDF导出,并且我需要从给定的ProjectPage
中提取所有SolutionPage
个对象 < / p>
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
答案 0 :(得分:3)
solution_page.content.stream_block.child_blocks["short_portfolio"]
将为您提供short_portfolio
块的定义,而不是该块的特定实例。为此,您需要遍历字段内容,在block_type
上查找匹配的块:
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)