首页 文章

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

提问于
浏览
1

假设我的模型如下 .

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 回答

  • 5

    我可以推荐别的吗?如果 email 字段在 Profile 的模型框架中,如果它与该模型无关,我不是很喜欢 .

    相反,如何只有两个表单并将初始数据传递给包含 email 的自定义数据?事情看起来像这样:

    forms.py

    # this name may not fit your needs if you have more fields, but you get the idea
    class UserEmailForm(forms.Form):
        email = forms.CharField()
    

    views.py

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

    然后,您将验证配置文件和用户电子邮件表单,但其他方面大致相同 .

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

    我更喜欢这种方法,因为它想知道为什么 emailemail 的一部分,当它不作为该模型上的字段存在时,为什么 email .

相关问题