On Jan 7, 1:04 pm, Andreas Pfrengle <a.pfren...@gmail.com> wrote:
> Hello,
>
> I am trying to implement a ChoiceField that's choices shall be
> calculated during form instantiation in the view depending on the
> users preferred language (according to request.LANGUAGE_CODE from
> LocaleMiddleware).
>
> Example forms.py:
> CHOICES = zip(
>     [x.number for x in MyModel.objects.all()],
>     [x.locale.get(lang=request.LANGUAGE_CODE).name for x in
> MyModel.objects.all()]
> )
> #locale is the manager from an generic relation (http://
> docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1)
>
> MyForm(forms.Form):
>     myfield = forms.ChoiceField(choices=CHOICES)
>

1. Maybe you could use ModelChoiceField:

http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

2. You could populate choices on each request, by writing custom
__init__ in MyForm:

def __init__(self, post=None, request=None):
        if post:
            super(MyForm, self).__init__(post)  # bound form
        else:
            super(MyForm, self).__init__()  # unbound form

        self.fields['myfield'].choices = zip(
    [x.number for x in MyModel.objects.all()],
    [x.locale.get(lang=request.LANGUAGE_CODE).name for x in
MyModel.objects.all()]

--
Tomasz Zielinski
http://pyconsultant.eu
-- 
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.


Reply via email to