我没有找到相关信息。而且我不确定是否可以这样做。所以我有以下Page
模型及其关系:
class TeamRooster(Page):
team_logo = models.ForeignKey(
'wagtailimages.Image',
null=True, blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
@register_snippet
class GroupstageTournamentModel(ClusterableModel):
team_1 = models.ForeignKey(
TeamRooster,
null=True, verbose_name='Erste Team',
on_delete=models.SET_NULL,
related_name="+",
)
class GroupstageScreencastRelationship(Orderable, models.Model):
page = ParentalKey('ScreencastPage',
related_name='groupstage_screencast_relationship')
match = models.ForeignKey('GroupstageTournamentModel',
related_name='match_screen_relationship')
panels = [
SnippetChooserPanel('match')
]
class ScreencastPage(Page):
content_panels = Page.content_panels + [
InlinePanel(
'groupstage_screencast_relationship', label="Choose Teams"
]
def matches(self):
matches = [
n.match for n in self.groupstage_screencast_relationship.all()
]
return matches
def serve(self, request):
if request.is_ajax():
result = [
{
'team_1_logo': match.team_1.team_logo
}
for match in self.matches()
]
json_output = json.dumps(result)
return HttpResponse(json_output)
else:
return super(ScreencastPage, self).serve(request)
是否可以使用ajax请求从TeamRooster
模型中获取图片?
如果我尝试按照上面的代码中所示执行此操作,那么我会收到错误:
TypeError: Object of type 'Image' is not JSON serializable
答案 0 :(得分:1)
图像记录本身可能没什么用处 - 您需要通过生成再现来指定它应显示的大小。这相当于使用{% image %}
模板标记:
http://docs.wagtail.io/en/v1.13.1/advanced_topics/images/renditions.html
您的代码将变为类似:
def serve(self, request):
if request.is_ajax():
result = []
for match in self.matches():
rendition = match.team_1.team_logo.get_rendition('fill-200x200')
result.append({
'team_1_logo': rendition.url,
'team_1_logo_width': rendition.width,
'team_1_logo_height': rendition.height,
})
json_output = json.dumps(result)
return HttpResponse(json_output)
else:
return super(ScreencastPage, self).serve(request)