2017-03-18 28 views
0

下面我粘貼用戶的配置文件編輯視圖的片段,我認爲這是沒有必要在這裏貼的所有視圖。我想設置初始數據,當用戶想要編輯他的配置文件時,他應該看到實際存儲在數據庫中的數據。設置inital表單數據

form = UserProfileForm(initial={'first_name': user.userprofile.first_name, 
            'last_name': user.userprofile.last_name, 
            'nickname': user.userprofile.nickname, 
            'bio': user.userprofile.bio, 
            'location': user.userprofile.location, 
            'gender': user.userprofile.gender, 
            'birth_date': user.userprofile.birth_date}) 

我上面的代碼創建的,它工作正常,但我認爲它不是Python的好,所以我的要求,我怎麼能寫的更好?

回答

2

而不是使用初始數據,則應該通過USERPROFILE本身作爲instance參數:

form = UserProfileForm(instance=user.userprofile) 

假設UserProfileForm是一個的ModelForm,這是應該的。發生

+0

錯誤** __ __的init(),因爲你不使用了一個意想不到的關鍵字參數「實例」 ** – dannyxn

+0

一個**的ModelForm **丹尼爾建議:https://docs.djangoproject.com/en/1.10/主題/表格/ modelforms/ – arie

+0

我已經改變了forms.Form到forms.ModelForm和它的作品!謝謝! – dannyxn