pythondjangodjango-forms

Overriding initial value in ModelForm


in my Django (1.2) project, I want to prepopulate a field in a modelform, but my new value is ignored. This is the snippet:

class ArtefactForm(ModelForm):
    material = CharField(widget=AutoCompleteWidget('material', force_selection=False))

    def __init__(self, *args, **kwargs):
        super(ArtefactForm, self).__init__(*args, **kwargs)
        self.fields['material'].initial = 'Test'

I also tried with self.base_fields, but no effect: there is always the database-value displaying in the form. Any ideas?


Solution

  • Try this:

    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial', {})
        initial['material'] = 'Test'
        kwargs['initial'] = initial
        super(ArtefactForm, self).__init__(*args, **kwargs)