1

I have a django view communicate the user's preferred locale to a form in forms.py. However, that form seems to get initialized before I even call it.

Class SurveyForm() seems to load before my call from views.py and even before the SurveyForms() init function becomes active.

Here is the code:

class SurveyForm(forms.Form):
    questions = Question.objects.all()
    Q1 = questions.get(identifier='Q1')
    question1 = forms.CharField(required=False, label=Q1.name)

    def __init__(self, *args, **kwargs):
        translation.activate('nl')

When I put translation.activate('nl') in the SurveyForm class, it does work. When I put translation.activate('nl') in the __init__, or in views.py, it does not work. How can this be changed?

Note: I use modeltranslation, so Q1.name will get the Dutch translation when Dutch language is active.

Jdruiter
  • 335
  • 2
  • 10

1 Answers1

2

Anything at class level is executed when the class is defined, on first import. You already know how to do things at instantation time - by doing it in the __init__ method.

It's not clear from your question what Q1 is. Is it a field? If so you can add it to self.fields; otherwise just set it directly on self.

def __init__(self, *args, **kwargs):
    translation.activate('nl')
    super(SurveyForm, self).__init__(*args, **kwargs)
    self.fields['Q1'] = ...
    # or
    self.Q1 = ...
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895