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

Python 如何在ModelForm中的自定义表单字段中预填充值,python,django,custom-fields,modelform,Python,Django,Custom Fields,Modelform,假设我有一个如下的模型 models.py 我有一个自定义字段email,如下所示 forms.py 在am设置中,设置上述modelform的一个实例,以便在编辑模板的表单中预先填充数据,如下所示 views.py 现在在表单中,我得到了Profile model下所有字段的所有预填充值,但是自定义字段是空的,这很有意义 但是有没有一种方法可以预先填充自定义字段的值?可能是这样的: email = forms.CharField(value = models.Profile.user.emai

假设我有一个如下的模型

models.py 我有一个自定义字段
email
,如下所示

forms.py 在am设置中,设置上述modelform的一个实例,以便在编辑模板的表单中预先填充数据,如下所示

views.py 现在在表单中,我得到了Profile model下所有字段的所有预填充值,但是自定义字段是空的,这很有意义

但是有没有一种方法可以预先填充自定义字段的值?可能是这样的:

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

我能推荐点别的吗?我不太喜欢在
Profile
的模型表单中包含
email
字段,如果它与该模型无关的话

相反,只需要两个表单并将初始数据传递到包含
电子邮件的自定义表单如何?所以事情会是这样的:

forms.py views.py 然后,您将验证配置文件和用户电子邮件表单,但在其他方面基本相同

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


我更喜欢这种方法,因为它不那么神奇,如果你在一年内回顾你的代码,你不会奇怪为什么在简单的扫描中,
电子邮件
模型表单
的一部分,而它在该模型上不作为字段存在。

我同意你的看法,在modelform中包含email字段是没有意义的。不过,在我的情况下,情况有点不同。另外,我刚刚阅读了
inital
的文档,对我来说似乎很有帮助。谢谢你的回答:)酷,我只是在做假设,但如果它有帮助,那就太棒了!快乐编码。
class ProfileForm(ModelForm):
    email = forms.CharField()
    class Meta:
         model = models.Profile

    fields = ('email', 'middle_name')
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))
email = forms.CharField(value = models.Profile.user.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()
profile = models.Profile.objects.get(user=request.user)
profileform = forms.ProfileForm(instance=profile)
user_emailform = forms.UserEmailForm(initial={'email': profile.user.email})