django-multilingual:按翻译字段排序下拉字段

时间:2010-01-26 09:45:43

标签: django django-forms django-multilingual

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

models.py:

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

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

template.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>

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:1)

我通过动态加载选择值解决了类似的问题。根本没有感觉脏。

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

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

答案 2 :(得分:0)

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