django-multilingual: order drop down field by translated field
how do i order a the options of a form field by a translated field?
models.py:
class UserProfile(models.Model):
...
country=models.ForeignKey('Country')
class Country(mo开发者_Python百科dels.Model):
class Translation(multilingual.Translation):
name = models.CharField(max_length=60)
...
template.html:
{# userprofileform is a standard modelform for UserProfile #}
{{ userprofileform.country }}
thank you
edit:
I want the options of the select
field to be ordered by name_de or name_en according to the language:
<!-- 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>
You could try using a custom widget in the form so that the sorting happens right before django would do the translation. Maybe this snippet from my current project can help
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')
I solved similar problem by loading choice values dynamically. Didn't feel dirty at all.
Example of getting values from Country model with name field containing country name. Using same logic, you can get your values from anywhere.
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
I don't have any real experience with i18n, so I don't know what's available to you on the backend, but you could use javascript to sort the menus in the browser
精彩评论