1
You should use OrderedDict
from collections import OrderedDict
class PersonneEnums(object):
LANGUE_ALBANAIS = 0
LANGUE_ALLEMAND = 1
...
TAB_LANGUE = OrderedDict((
(LANGUE_ALBANAIS, _(u'Albanian')),
(LANGUE_ALLEMAND, _(u'German')),
...
))
This way all your items will be ordered the way you put them in TAB_LANGUE
.
And then you should use .items()
class ProfileForm(forms.ModelForm):
class Meta:
model = Personne
fields = ('blablafields',)
e = {'required': _(u'This field is required'),
'invalid': _(u'This field contains invalid data')}
a = _(u'Mother tongue:')
langue = forms.IntegerField(
label=a, required=True,
widget=forms.Select(attrs={
'title': a,
'groupno': 2,
'class': 'form-control', },
choices=(('', '--'),) + tuple(PersonneEnums.TAB_LANGUE.items()),
error_messages=e)
Update
Also there is very cool third party django app called dj.choices. It is very helpful for this kind of tasks.
0
how about this solution:
langues_classees = sorted(PersonneEnums.TAB_LANGUE.items(), key=lambda t: t[1])
.items()
does exactly the same as [(k, dictionnaire[k]) for k in dictionnaire]
Also, if you ever need to interface this with any other language management tools at some point, you should use ISO language codes (e.g. ar for arabic, hy for armenian, en for english, zh for chinese, etc.) instead of coming up with your own codes
UPDATE:
The solution above may not be adapted to your use case, because you may want the sorting to happen at the time of the request and depend on the browser’s language (‘German’ comes after ‘Arabic’ in English but in French, ‘Allemand’ comes before ‘Arabe’) rather than when the Form class is declared.
Check a solution for a “Lazy choice field” at https://www.djangosnippets.org/snippets/1767/
- How do i print data from a database in column format?
- Extending a model in Django
- No module name 'celery' after migrate
- Django : Heroku deploy Error 500 on app pages but admin working