How to set initial values for a ModelForm when instance is also given

后端 未结 3 1409
庸人自扰
庸人自扰 2021-01-02 06:54

It seems like if a ModelForm is given an instance, it ignores any values you provide for initial and instead sets it to the value of the instance -- even if tha

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 07:21

    You can also pass extra variables to the class when initializing it. The values you pass can then override initial or POST data.

    class RegisterForm(forms.ModelForm):
        ... fields here ...
    
        def __init__(self, person, conference, *args, **kwargs):
            ... other code ...
            super(RegisterForm, self).__init__(*args, **kwargs)
            self.fields['person'] = person
            self.fields['conference'] = conference
    
    form = RegisterForm(person, conference, initial=initial, instance=registration)
    

提交回复
热议问题