Thought about it after a few searches.
You must set the initial value before calling super .
So, instead of scrolling through self.fields.keys() , I had to enter a list of the fields I wanted and looped over them:
class RegisterForm(forms.ModelForm): ... fields here ... initial_fields = ['first_name', 'last_name', ... ] def __init__(self, *args, **kwargs): ... other code ... self.person = kwargs.pop('person') for key in self.initial_fields: if hasattr(self.person, key): self.fields[k].initial = getattr(self.person, key) super(RegisterForm, self).__init__(*args, **kwargs)
@ Daria rightly points out that before you call super, you do not have self.fields . I am sure this will work:
class RegisterForm(forms.ModelForm): ... fields here ... initial_fields = ['first_name', 'last_name', ... ] def __init__(self, *args, **kwargs): ... other code ... initial = kwargs.pop('initial', {}) self.person = kwargs.pop('person') for key in self.initial_fields: if hasattr(self.person, key): initial[key] = initial.get(key) or getattr(self.person, key) kwargs['initial'] = initial super(RegisterForm, self).__init__(*args, **kwargs)
In this version, we use the initial argument to pass values ββto. It is also written so that if we already have a value in the source for this field, we do not overwrite it.
source share