Setting initial Django form field value in the __init__ method
I had that exact same problem and I solved it doing this:
def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) kwargs.update(initial={ # 'field': 'value' 'km_partida': '1020' }) super(ViagemForm, self).__init__(*args, **kwargs) # all other stuff
Try this way:
super(ViagemForm, self).__init__(*args, **kwargs)if field_value: #self.initial[field_name] = field_value self.fields[field_name].initial = field_value
I want to mention, although this might not solve your problem, that an 'initial' dict kwarg sent to a form appears to get preference over field['field_name'].initial
.
class MyView(View): form = MyForm(initial={'my_field': 'first_value'})class MyForm(Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['my_field'].initial = 'second_value'
my_field
rendered will have initial set to 'first_value'
.
Some options (among others) might be:
Determine second_value
in the view before initializing the form:
class MyView(View): # determine second_value here form = MyForm(initial={'my_field': 'second_value'})
replace first_value
with second_value
in initial
before calling super()
:
class MyForm(Form): def __init__(self, *args, **kwargs): # determine second_value here if kwargs.get('initial', None): kwargs['initial']['my_field'] = 'second_value' super().__init__(*args, **kwargs)
Make sure 'first_value'
isn't in kwargs['initial']
before calling super()
:
class MyForm(Form): def __init__(self, *args, **kwargs): if kwargs.get('initial', None): if kwargs['initial']['my_field'] del(kwargs['initial']['my_field'] super().__init__(*args, **kwargs) # determine second_value here self.fields['my_field'].initial = 'second_value'