使用代码段数据填充ChoiceBlock

时间:2016-10-31 14:28:40

标签: python-3.x django-1.8 wagtail

我有一个国家/地区代码片段,我想在每个本地化网站的根页面上定义本地化的国家/地区名称。

该代码段如下所示:

@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 []

现在我想在创建一个选择块时调用函数get_iso_codes并填充代码片段中的选项。

该块看起来像这样

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

但是,在调用manage.py makemigrations时,我收到以下错误:

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

我可以通过评论' Country.objects.all()'来绕过这个。然后运行makemigrations,然后再次读取代码行,但是我更喜欢不需要这种解决方法的解决方案(当我运行' manage.py collectstatic'在部署之前构建时,我也会失败)我不知道如何解决这个问题并且陷入困境)

1 个答案:

答案 0 :(得分:0)

我找到了基于Wagtail, how do I populate the choices in a ChoiceBlock from a different model?

的解决方案

国家/地区类别保持不变(除了get_iso_codes方法现在是超级的)。我刚刚扩展了Chooserblock并使用Country作为我的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

并使用CountryChooserBlock而不是ChoiceBlock:

class CountryLocalizedBlock(blocks.StructBlock):
    iso_code = CountryChooserBlock(unique=True)
    localized_name = blocks.CharBlock(required=True)