【问题标题】:django-multilingual: order drop down field by translated fielddjango-multilingual:按翻译字段排序下拉字段
【发布时间】:2011-01-09 11:04:14
【问题描述】:

如何按翻译字段排序表单字段的选项?

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

【问题讨论】:

  • 你能说得更具体点吗? “按另一个字段排序一个字段”到底是什么意思?也许举个例子会有所帮助。

标签: django django-forms django-multilingual


【解决方案1】:

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

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')

【讨论】:

    【解决方案2】:

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

    从 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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-06-03
        • 1970-01-01
        • 1970-01-01
        • 2015-07-24
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        相关资源
        最近更新 更多