1

I have a snippet for countrycodes and I want to define localized country names on the root pages for each localized site.

The snippet looks like this:

@register_snippet
class Country(models.Model):
    iso_code = models.CharField(max_length=2, unique=True)

panels = [
    FieldPanel('iso_code'),
]

def get_iso_codes():
    try:
        countries = Country.objects.all()
        result = []
        for country in countries:
            result.append((country.iso_code,country.iso_code))
        return result
    except Country.DoesNotExist:
        return []

Now I want to call the function get_iso_codes when creating a choiceblock and fill the choices from the snippet.

The block looks like this

class CountryLocalizedBlock(blocks.StructBlock):
    iso_code = blocks.ChoiceBlock(choices=Country.get_iso_codes(), unique=True)
    localized_name = blocks.CharBlock(required=True)

However, when calling manage.py makemigrations I get the following error:

psycopg2.ProgrammingError: relation "home_country" does not exist
LINE 1: ..."."iso_code", "home_country"."sample_number" FROM "home_coun...

I can bypass this by commenting out 'Country.objects.all()' and then running makemigrations and later readding the line again to the code, however I would prefer a solution that does not require this workaround (also it fails when I run 'manage.py collectstatic' when building before deployment and I don't know how to work around this and am stuck)

realheri
  • 133
  • 9

1 Answers1

1

I found a solution based on Wagtail, how do I populate the choices in a ChoiceBlock from a different model?

The country class remains untouched (except that the get_iso_codes method is now superflous). I've just extended Chooserblock and use Country as my target_model:

class CountryChooserBlock(blocks.ChooserBlock):
    target_model = Country
    widget = forms.Select

    def value_for_form(self, value):
        if isinstance(value, self.target_model):
            return value.pk
        else:
            return value

And used the CountryChooserBlock instead of the ChoiceBlock:

class CountryLocalizedBlock(blocks.StructBlock):
    iso_code = CountryChooserBlock(unique=True)
    localized_name = blocks.CharBlock(required=True)
Community
  • 1
  • 1
realheri
  • 133
  • 9