2

翻訳されたフィールドでフォームフィールドのオプションを並べ替えるにはどうすればよいですか?

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>
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 に答える
0

私は i18n の実際の経験がないので、バックエンドで何が利用できるかはわかりませんが、javascript を使用してブラウザのメニューを並べ替えることができます

于 2010-01-26T16:27:44.330 に答える