2017-03-18 31 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