我正在制作一个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)
以及forms.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})
而不是“People”,它应该说“Mensen”(如.po文件,我没有忘记编译)。有什么想法吗?
答案 0 :(得分:0)
我想我可以解决这个问题,因为它不是模型形式,而是可能是选择本身的问题。 知道选择被保存为关键整数。
现在找到解决方案,希望能在网上研究一下后解决您的问题:
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_choices
与choices=translate_choices(CHOICES)
对话。
Hoop dat dit je wat verder helpt;)
答案 1 :(得分:0)
我找到了让它发挥作用的方法。说实话,我不了解这里发生的事情的每个方面,但我从相关问题中一起困惑。
解决方法似乎是创建一个显式模型并使用惰性版本的ChoiceField。我找到了后者here的代码。这是我的forms.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得到了这个想法。
并不是说我不知道为什么这样有效,但它在我的脑海里并不像现在这样敏锐,所以如果有人对此有任何进一步的见解这是必要的,为什么它有效,它们仍然受欢迎。
答案 2 :(得分:0)