我对Django Wagtail相对较新,我正在关注docs.wagtail.io网站上的演示,可以找到here关于如何使用InlinePanel添加链接列表的相关链接 我似乎遇到了一个错误,我不完全理解它的含义。 错误说
AttributeError: type object 'BookPageRelatedLinks' has no attribute 'rel'
演示代码如下
from wagtail.wagtailcore.models import Orderable, Page
from modelcluster.fields import ParentalKey
from wagtail.wagtailadmin.edit_handlers import FieldPanel,InlinePanel
from django.db import models
class BookPage(Page):
# The abstract model for related links, complete with panels
class RelatedLink(models.Model):
title = models.CharField(max_length=255)
link_external = models.URLField("External link", blank=True)
panels = [
FieldPanel('title'),
FieldPanel('link_external'),
]
class Meta:
abstract = True
# The real model which combines the abstract model, an
# Orderable helper class, and what amounts to a ForeignKey link
# to the model we want to add related links to (BookPage)
class BookPageRelatedLinks(Orderable, RelatedLink):
page = ParentalKey('demo.BookPage', related_name='related_links')
content_panels = Page.content_panels + [
InlinePanel('BookPageRelatedLinks', label="Related Links"),
]
我的主要目标是了解这一点,以便将图片链接添加到我正在开发的BlogPage应用的侧边栏上。
答案 0 :(得分:1)
您的InlinePanel
声明不太正确 - 需要:
InlinePanel('related_links', label="Related Links")
这是发生了什么:
related_name='related_links'
定义ParentalKey,您可以在BookPage上设置名为related_links
的一对多关系。这允许您检索与给定BookPage实例关联的所有BookPageRelatedLinks
对象(例如,如果您的BookPage实例被称为page
,则可以编写page.related_links.all()
)。InlinePanel
声明然后告诉Wagtail在管理员中编辑related_links
属性。您收到误导性错误消息的原因是您已在RelatedLink
内定义了BookPageRelatedLinks
和BookPage
类 - 这有点不寻常,但仍然有效。这导致BookPageRelatedLinks
被定义为BookPage的属性(即BookPage.BookPageRelatedLinks
)。然后,当Wagtail尝试设置InlinePanel时,它会检索该属性并失败,因为它不是预期的对象类型(它是类定义,而不是关系)。
如果您以更传统的方式编写模型文件,使用下面(或上面)定义的相关模型BookPage
:
class BookPage(Page):
content_panels = Page.content_panels + [
InlinePanel('BookPageRelatedLinks', label="Related Links"),
]
# The abstract model for related links, complete with panels
class RelatedLink(models.Model):
title = models.CharField(max_length=255)
link_external = models.URLField("External link", blank=True)
panels = [
FieldPanel('title'),
FieldPanel('link_external'),
]
class Meta:
abstract = True
# The real model which combines the abstract model, an
# Orderable helper class, and what amounts to a ForeignKey link
# to the model we want to add related links to (BookPage)
class BookPageRelatedLinks(Orderable, RelatedLink):
page = ParentalKey('home.BookPage', related_name='related_links')
...然后你会得到一个更具信息性的错误:AttributeError: type object 'BookPage' has no attribute 'BookPageRelatedLinks'
。