Wagtail,如何在不同模型中填充ChoiceBlock中的选项? [英] Wagtail, how do I populate the choices in a ChoiceBlock from a different model?
问题描述
这是显示在文本顶部的图标的模型,它们会获得一个名称和图标。
This is the model for icons displayed on top of a text, they get a name and the icon.
from django.db import models
from django.utils.translation import ugettext as _
from django.conf import settings
class SomeSortOfIcon(models.Model):
name = models.CharField(max_length=200,
verbose_name=_('Icon Name'),
help_text=_('This value will be shown to the user.'))
image = models.ForeignKey(
getattr(settings, 'WAGTAILIMAGES_IMAGE_MODEL', 'wagtailimages.Image'),
on_delete=models.PROTECT,
related_name='+',
verbose_name=_('Icon'),
)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Icon')
verbose_name_plural = _('Icons')
这是代码fo r将要添加到页面中的流域的块。
This is the code for the Block that's going to be added into a streamfield onto the page.
from django.db import models
from django import forms
from django.utils.translation import ugettext as _
from wagtail.wagtailcore import blocks
from xxx.models import SomeSortOfIcon
class SomeSortOfIconChooserBlock(blocks.ChoiceBlock):
## PROBLEM HERE, where do I get the choices from?
choices = tuple([(element.name, element.image) for element in SomeSortOfIcon.objects.all()])
target_model = SomeSortOfIcon
class SomeBox(blocks.StructBlock):
headline = blocks.TextBlock(required=True)
some_icon = SomeSortOfIconChooserBlock(label='Icon', required=True)
info_box_content = blocks.RichTextBlock(label='Content', required=True)
class Meta:
template = 'blocks/some_box.html'
icon = 'form'
label = _('Some Box')
所以,我做获取块添加到流域,对于图标,我想要一个下拉菜单与图标模型的选择。它应该显示名称,当你选择一个,它将被自动添加到名称到html。
So, I do get the Block added to the streamfield and for the icon I want a dropdown menu with the choices from the icon model. It's supposed to display the name and when you chose one it is going to be automatically added by name into the html.
我得到下拉菜单,但它是空的。我尝试使用选择属性,但我不知道如何将其连接到其他模型。
I get the dropdown menu, but it is empty. I tried to use the choices attribute, but I don't know how to connect it to the other model.
有人可以帮忙吗?
推荐答案
您可以通过继承ChooserBlock来实现。
You can do that by inheriting from the ChooserBlock.
class SomeSortOfIconChooserBlock(blocks.ChooserBlock):
target_model = SomeSortOfIcon
widget = forms.Select
class Meta:
icon = "icon"
# Return the key value for the select field
def value_for_form(self, value):
if isinstance(value, self.target_model):
return value.pk
else:
return value
并在你的块中使用
class SomeBox(blocks.StructBlock):
headline = blocks.TextBlock(required=True)
some_icon = SomeSortOfIconChooserBlock(required=True)
info_box_content = blocks.RichTextBlock(label='Content', required=True)
class Meta:
template = 'blocks/some_box.html'
icon = 'form'
label = _('Some Box')
这将给你一个基于 SomeSortOfIcon
模型的对象。
This will give you a drop down based on the objects of the SomeSortOfIcon
model.
这篇关于Wagtail,如何在不同模型中填充ChoiceBlock中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!