Wagtail, how do I fill in a selection in ChoiceBlock from another model?

This is the model for the icons displayed on top of the text, they get the name and 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')

This is the code of the block that will be added to the streaming field on 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')

So, I get the block added to the streamfield field, and for the icon I want a dropdown menu with a choice from the icon model. It should display the name, and when you select it, it will be automatically added by name in html.

I get a drop down menu, but it's empty. I tried to use the selection attribute, but I do not know how to connect it to another model.

Can anybody help? It would be very grateful.

+4
source share
1 answer

, 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.

+3

Source: https://habr.com/ru/post/1649916/


All Articles