Re: How to lazy-sort a list of translation strings alphabetically

2010-01-26 Thread Andreas Pfrengle
On 25 Jan., 20:36, Matthias Kestenholz 
wrote:
> Alternatively, you could write your own Field or
> Widget which implements the sorting -- it's not that hard.

I was just starting to write "It doesn't work" when I found this here:
http://www.djangosnippets.org/snippets/1767/

class LazyChoiceField(forms.ChoiceField):
def __init__(self, *args, **kwargs):
# remove choices from kwargs
self._lazy_choices = kwargs.pop('choices',())
super(LazyChoiceField,self).__init__(*args, **kwargs)

def __deepcopy__(self, memo):
result = super(LazyChoiceField,self).__deepcopy__(memo)
result.choices = self._lazy_choices
result.choices.sort(lambda x, y: cmp(x[1], y[1]))
return result

Just needed to add the line with the sorting to the snippet. Well,
actually I don't really understand why it works and when django calls
the __deepcopy__, but supposedly it is called after the translation
takes place, so this is an effective solution. Could be generalized
further (not hardcode the sorting function), but for now it does the
job.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



How to lazy-sort a list of translation strings alphabetically

2010-01-17 Thread Andreas Pfrengle
For a multilingual project, I have a ChoiceField and want to display
the choices in alphabetical order - according to the current language.
Example:
choices = ((1, _('Some choice')), (2, _('Another choice')), (3, _('One
more choice')))

In English it should be ordered 'Another choice', 'One more choice',
'Some choice', but in another language the ordering could be
different.
Can I define a sort-function that is called lazily? I've looked at the
lazy and allow_lazy functions of django.utils.functional, but didn't
really understand how it works.

I think another possibility would be to define the choices in the
form's __init__ at runtime, but that doesn't seem like an elegant way
to solve the problem.

Any ideas?
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.