Django - ModelForm Dynamic field update

后端 未结 4 824
情书的邮戳
情书的邮戳 2021-01-06 11:50

I\'m trying to update certain fields a ModelForm, these fields are not fixed. (I have only tutor that is autopopulated by the view)

Model:



        
4条回答
  •  伪装坚强ぢ
    2021-01-06 12:45

    You can invoke form's constructor like this:

    class SessionForm(forms.ModelForm):
        class Meta:
            model = Session
            exclude = ['tutor', 'start_time']
    
        def __init__(self, your_extra_args, *args, **kwargs):
            super(SessionForm, self).__init__(*args, **kwargs)
            if need_end_time_start_time(your_extra_args):
                self.fields['start_time'] = forms.DateTimeField()     
    

    To use this class, you have to pass an argument "your_extra_args" to your form:

    session_form = SessionForm('foo')
    

提交回复
热议问题