Forms.py:
from django import forms
from django.forms.formsets import BaseFormSet, formset_factory
class RequestFormSet(BaseFormSet):
"""
Formset that passes the HttpRequest on to every Form's __init__
Suitable to populate Fields dynamically depending on request
"""
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(RequestFormSet, self).__init__(*args, **kwargs) #this calls _construct_forms()
def _construct_forms(self): #this one is merely taken from django's BaseFormSet
# except the additional request parameter for the Form-constructor
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i, request=self.request))
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField() # choices will be created dynamically
def __init__(self, *args, **kwargs):
request = kwargs.pop('request', None)
super(MyFormForm, self).__init__(*args, **kwargs)
# the rest is just an example that looks up the LANGUAGE_CODE,
# pulls the right translation from the database and creates
# my_choice_field's choices from it. You can do here whatever you want with request
if request:
LANG = request.LANGUAGE_CODE #needs LocaleMiddelware or raises AttributeError
self.fields['my_choice_field'].choices = zip(
[x.number for x in MyModel.objects.all()],
[x.locale.get(language__iexact=LANG).name for x in MyModel.objects.all()]
)
MyFormSet = formset_factory(MyForm, formset=RequestFormSet)
Views.py:
my_view(request):
# ...
formset = MyFormSet(request=request)
form = MyForm(request=request)
# ...
Comments
Thank you very much. I was twisting my head with this one.
#