djangowagtailwagtail-admin

Can't save custom optional ChooserBlock when blank


Came across the very same issue that is well described here : https://github.com/wagtail/wagtail/issues/7344#issue-946329708 but the fix doesn't seem to work in my case.

Basically I have a custom ChooserBlock supposed to make it possible to tie a model's given instance to a StructBlock. Rendering works differently if the ChooserBlock value is blank or not, so it is quite important that it actually can be blank.

But when left blank i stamble upon this error when trying to save :

Field 'id' expected a number but got ''.

The error's stack is exactly the same as the one depicted in the github issue I linked above.

I tried the given fix but it doesn't seem to make any difference, at least for my issue.

class CommunityChooserBlock(blocks.ChooserBlock):
target_model = Community
widget = forms.Select

# Return the key value for the select field
def value_for_form(self, value):
    if value == "":
        return None
    else:
        return super().value_from_form(value)

Did I miss anything ?

Edit: I've also tried to override the get_prep_value and clean methods but it didn't change anything.

def get_prep_value(self, value):
    if value == '':
        return None
    else:
        super().get_prep_value(value)


def clean(self, value):
    if value == '':
        value = None
    super().clean(value)

Solution

  • Update : I couldn't come up with a proper fix, so I changed my plans and went for a ChoiceBlock with dynamic choices list, as described here : https://stackoverflow.com/a/60979072/13934028.

    It seems to work just fine for my case