Django模型中的选项没有被翻译,可能是因为使用了modelform或modelformset?

2024-03-29 12:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个Django项目,把有行为问题的狗和能帮助主人克服这些问题的人联系起来。项目的大部分内容已经被翻译,但是有一些字符串没有被翻译。你知道吗

以下是相关模型:

from django.utils.translation import ugettext_lazy as _

class Issue(models.Model):

    PEOPLE = 'PE'
    OWNERS = 'OW'
    EXPERIENCED_PEOPLE = 'EX'

    HELPER_CHOICES = ((PEOPLE, _('People')),
                      (OWNERS, _('Owners')),
                      (EXPERIENCED_PEOPLE, _('People with experience')))

    who_can_help = models.CharField(_('Who can help?'),
                                    blank=False,
                                    choices=HELPER_CHOICES,
                                    default=PEOPLE,
                                    max_length=2,
                                    null=False)
    doggo = models.ForeignKey(Doggo, on_delete=models.CASCADE)

以及表单.py你知道吗

IssueFormSet = modelformset_factory(Issue, fields=['title', 'description', 'plan', 'who_can_help'])

最后,视图(我省略了处理POST请求的部分):

def doggo_create_view(request):
    doggo_form = DoggoForm()
    issue_formset = IssueFormSet(queryset=Issue.objects.none())
    return render(request, 'doggos/doggo_form.html', {'form': doggo_form, 'formset': issue_formset})

我看到的是:missing translation

它应该说“Mensen”,而不是“People”(在.po文件中,我还没有忘记编译它)。有什么想法吗?你知道吗


Tags: 项目formhelpermodelshelpissuepeoplecan
2条回答

我找到了一个办法让它工作。说实话,我不太了解这里发生的每一个方面,但我从相关的问题上把它弄得一头雾水。你知道吗

解决方法似乎是创建一个显式的modelform并使用ChoiceField的延迟版本。我找到了后者的代码here。这是我的表单.py地址:

class LazyChoiceField(ChoiceField):
    '''
    A Lazy ChoiceField.
    This ChoiceField does not unwind choices until a deepcopy is called on it.
    This allows for dynamic choices generation every time an instance of a Form is created.
    '''
    def __init__(self, *args, **kwargs):
        # remove choices from kwargs.
        # choices should be an iterable
        self._lazy_choices = kwargs.pop('choices',())
        super(LazyChoiceField,self).__init__(*args, **kwargs)

    def __deepcopy__(self, memo):
        result = super(LazyChoiceField,self).__deepcopy__(memo)
        lz = self._lazy_choices
        if callable(lz):
            lz = lz()
        result.choices = lz
        return result

class IssueForm(forms.ModelForm):

    who_can_help = LazyChoiceField(choices=((PEOPLE, _('People')),
                                            (OWNERS, _('Owners')),
                                            (EXPERIENCED_PEOPLE, _('People with experience'))))

    class Meta:
        model = Issue
        fields = ['title', 'description', 'plan']

我是从this similar issue那里得到这个主意的。你知道吗

并不是说我不知道为什么这样做,但在我的脑海里它还没有那么清晰,所以如果有人对为什么需要这样做以及为什么这样做有任何进一步的见解,他们仍然是受欢迎的。你知道吗

我想我也许能解决这个问题,因为这不是模型集,而是选择本身的问题。 知道选择被保存为关键整数。你知道吗

现在,我希望在网络上研究一下后,能解决您的问题的解决方案是:

from django.utils.translation import ugettext_lazy as _

def translate_choices(choices):
    """
        Returns tuples of localized choices based on the dict choices parameter.
        Uses lazy translation for choices names.
    """
    return tuple([(k, _(v)) for k, v in choices.items()])

class Issue(models.Model):

    PEOPLE = 'PE'
    OWNERS = 'OW'
    EXPERIENCED_PEOPLE = 'EX'

    HELPER_CHOICES = ((PEOPLE, _('People')),
                      (OWNERS, _('Owners')),
                      (EXPERIENCED_PEOPLE, _('People with experience')))

    who_can_help = models.CharField(_('Who can help?'),
                                    blank=False,
                                    choices=translate_choices(HELPER_CHOICES),
                                    default=PEOPLE,
                                    max_length=2,
                                    null=False)
    doggo = models.ForeignKey(Doggo, on_delete=models.CASCADE)
  • 可以对其他选项字段重复使用translate\u choices函数。你知道吗
  • 坏的一面:垃圾箱/制造_消息.py无法自动获取选项值,您必须手动将它们添加到.po中。你知道吗

这里有一个简单的循环来翻译每个选项,您可以通过设置choices=translate_choices(CHOICES)translate_choices对话。你知道吗

Hoop dat dit je wat verder helpt;)

相关问题 更多 >