我如何在另一个称为资源的代码段中使用类别代码段?我想按类别过滤资源列表,并且类别是其自己的摘录。尝试创建资源时出现此错误:
AttributeError at /admin/snippets/home/resource/add/
'ForwardManyToOneDescriptor' object has no attribute 'rel'
这是我的代码:
class Resource(models.Model):
"""Snippet for Resources"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
resource_name = models.CharField(max_length=128, blank=False, null=True)
phone_number = models.CharField(max_length=12, blank=True, null=True)
website = models.URLField(blank=True, null=True)
info = RichTextField(blank=True, null=True)
category = models.ForeignKey('ResourceCategory', on_delete=models.CASCADE, null=True, blank=True)
panels = [
MultiFieldPanel(
[
FieldPanel("resource_name"),
FieldPanel("phone_number"),
],
heading="Resource information"
),
MultiFieldPanel(
[
FieldPanel('website')
],
heading="Links"
),
MultiFieldPanel(
[
FieldPanel('info')
],
heading="Info"
),
MultiFieldPanel(
[
InlinePanel("category", label="Category")
]
)
]
def __str__(self):
"""String representation of this class"""
return self.resource_name
class Meta:
verbose_name = "Resource"
verbose_name_plural = "Resources"
register_snippet(Resource)
class ResourceCategory(models.Model):
"""Snippet for Resources"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
category_name = models.CharField(max_length=128, blank=False, null=True)
panels = [
MultiFieldPanel(
[
FieldPanel('category_name')
],
heading="Category"
)
]
def __str__(self):
"""String representation of this class"""
return self.category_name
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
register_snippet(ResourceCategory)
答案 0 :(得分:1)
category
字段应使用FieldPanel('category')
,而不是InlinePanel
。 InlinePanel用于管理属于该片段的多个子对象,但是这里的Resource仅属于一个ResourceCategory。
(如果您确实打算允许资源属于多个类别,则需要调整模型,以便Resource具有子模型,其中包含ParentalKey
到Resource和ForeignKey
到ResourceCategory。)