How to pass initial parameter to django's ModelForm instance?

前端 未结 4 1620
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 05:01

The particular case I have is like this:

I have a Transaction model, with fields: from, to (both are ForeignKeys to auth.Use

4条回答
  •  粉色の甜心
    2021-01-31 05:23

    I ran into this problem as well, and this was my solution:

    class ChangeEmailForm(forms.ModelForm):
        def __init__(self, user, *args, **kwargs):
            self.user = user
            super(ChangeEmailForm, self).__init__(*args, **kwargs)
            self.fields['email'].initial = user.email
    
        class Meta:
            model = User
            fields = ('email',)
    
        def save(self, commit=True):
            self.user.email = self.cleaned_data['email']
            if commit:
                self.user.save()
            return self.user
    

提交回复
热议问题