如何在ModelForm中的自定义表单字段中预填充值

时间:2012-12-20 12:26:15

标签: python django custom-fields modelform

假设我有一个模型如下。

models.py

class Profile(models.Model):
    user = models.OneToOneField(User)
    middle_name = models.CharField(max_length=30, blank=True, null=True)

我在ModelForm中有一个自定义字段email,如下所示

forms.py

class ProfileForm(ModelForm):
    email = forms.CharField()
    class Meta:
         model = models.Profile

    fields = ('email', 'middle_name')

在am中设置上述模型的实例,以便在编辑模板的表单中预填充数据,如下所示。

views.py

def edit_profile(request):
    profile = models.Profile.objects.get(user=request.user)
    profileform = forms.ProfileForm(instance=profile)
    return render_to_response('edit.html', { 'form' : 'profileform' }, context_instance=RequestContext(request))

现在,在表单中,我获取了为Profile模型下的所有字段预填充的所有值,但自定义字段为空,这是有道理的。

但有没有办法预先填写自定义字段的值?也许是这样的:

email = forms.CharField(value = models.Profile.user.email)

1 个答案:

答案 0 :(得分:6)

我可以推荐别的吗?如果email模型中的Profile字段与email无关,那么我就不喜欢它。

相反,如何只使用两个表单并将初始数据传递到包含# this name may not fit your needs if you have more fields, but you get the idea class UserEmailForm(forms.Form): email = forms.CharField() 的自定义表单?事情看起来像这样:

forms.py

profile = models.Profile.objects.get(user=request.user)
profileform = forms.ProfileForm(instance=profile)
user_emailform = forms.UserEmailForm(initial={'email': profile.user.email})

views.py

email

然后,您正在验证个人资料和用户电子邮件表单,但其他方面大致相同。

我假设你没有在Profile ModelForm和这个UserEmailForm之间共享逻辑。如果您需要配置文件实例数据,您可以随时传递它。

我更喜欢这种方法,因为它不那么神奇,如果你回顾一年中的代码,你就不会想知道为什么{1}}是ModelForm的一部分。当它不存在于该模型上的字段时。