设置初始表格数据

时间:2017-03-18 20:15:28

标签: django forms user-profile

下面我粘贴用户个人资料版本视图的片段,我认为没有必要在此处粘贴所有视图。我想设置初始数据,当用户想要编辑他的个人资料时,他应该看到实际存储在数据库中的数据。

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})

我已经创建了上面的代码并且它工作正常,但我认为它根本不是pythonic,所以我的请求是关于如何更好地编写它?

1 个答案:

答案 0 :(得分:2)

您应该将userprofile本身作为instance参数传递,而不是使用初始数据:

form = UserProfileForm(instance=user.userprofile)

假设UserProfileForm是ModelForm,应该是它。