On 7 Jan., 13:22, Tomasz Zieliński <tomasz.zielin...@pyconsultant.eu> wrote: > 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 Zielinskihttp://pyconsultant.eu
Hello Tomasz, thanks for the quick answer, however your first suggestion doesn't work, since I don't want a queryset, I just want to display a field of a related model for every model in the queryset. The second variant seems to work, even though I always get the result for German language. But I suppose the problem is rather untested i18n in my project than the formfield However I'm wondering how I would transform this concept on Formsets. I think I would somehow need to expand already the formsets __init__ to accept the additional 'request' parameter (otherwise I get "__init__ () got an unexpected keyword argument 'request'"), and then push it forward to the forms __init__.
-- 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.