2

我如何通过翻译字段订购表单字段的选项?

模型.py:

class UserProfile(models.Model):
    ...
    country=models.ForeignKey('Country')

class Country(models.Model):
    class Translation(multilingual.Translation):
        name = models.CharField(max_length=60)
    ...

模板.html:

{# userprofileform is a standard modelform for UserProfile #}
{{ userprofileform.country }}

谢谢你

编辑:

我希望select根据语言按 name_de 或 name_en 对字段的选项进行排序:

<!-- English -->
<select>
    <option>Afganistan</option>
    <option>Austria</option>
    <option>Bahamas</option>
</select>

<!-- German (as it is) -->
<select>
    <option>Afganistan</option>
    <option>Österreich</option>
    <option>Bahamas</option>
</select>

<!-- German (as it should be) -->
<select>
    <option>Afganistan</option>
    <option>Bahamaas</option>
    <option>Österreich</option>
</select>
4

3 回答 3

1

您可以尝试在表单中使用自定义小部件,以便在 django 进行翻译之前进行排序。也许我当前项目中的这个片段可以提供帮助

import locale
from django_countries.countries import COUNTRIES
from django.forms import Select, Form, ChoiceField

class CountryWidget(Select):

    def render_options(self, *args, **kwargs):
        # this is the meat, the choices list is sorted depending on the forced 
        # translation of the full country name. self.choices (i.e. COUNTRIES) 
        # looks like this [('DE':_("Germany")),('AT', _("Austria")), ..]
        # sorting in-place might be not the best idea but it works fine for me
        self.choices.sort(cmp=lambda e1, e2: locale.strcoll(unicode(e1[1]),
           unicode(e2[1])))
        return super(CountryWidget, self).render_options(*args, **kwargs)

class AddressForm(Form):
    sender_country = ChoiceField(COUNTRIES, widget=CountryWidget, initial='DE')
于 2012-04-25T00:05:51.380 回答
1

我通过动态加载选择值解决了类似的问题。一点也不觉得脏。

从 Country 模型中获取值的示例,其中 name 字段包含国家名称。使用相同的逻辑,您可以从任何地方获取您的值。

from django.utils.translation import ugettext_lazy as _
from mysite.Models import Country

class UserProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        self.fields['country'].queryset = Country.objects.order_by(_('name'))

    class Meta:
        model = Country
于 2017-05-11T06:25:39.030 回答
0

我对 i18n 没有任何实际经验,所以我不知道后端有什么可供您使用,但您可以使用 javascript 对浏览器中的菜单进行排序

于 2010-01-26T16:27:44.330 回答