Pass initial value to a modelform in django

前端 未结 3 2182
渐次进展
渐次进展 2021-02-13 20:22

How can I pass an initial value for a field to a model form. I have something like the following code

class ScreeningForm(forms.ModelForm):
    class Meta:
             


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 20:49

    As your ModelForm is bound to the Person-Model, you could either pass a Person-Instance:

    form = PersonForm(instance=Person.objects.get(foo=bar)
    

    or overwrite the ModelForm's init-method:

    class PersonForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
           super(PersonForm, self).__init__(*args, **kwargs)
           self.fields['foo'].value = 'bar'
    
        class Meta:
            model = Person
            exclude = ['name']
    

    This is untested. I'm not sure whether "value" is correct, I'm not having a Django-Installation here, but basically this is the way it works.

提交回复
热议问题