【问题标题】:How can I prefill value in a custom form field in a ModelForm如何在 ModelForm 的自定义表单字段中预填充值
【发布时间】:2012-12-20 12:26:15
【问题描述】:

假设我有一个模型如下。

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

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

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)

【问题讨论】:

    标签: python django custom-fields modelform


    【解决方案1】:

    我可以提出其他建议吗?如果 email 与该模型无关,我不喜欢在 Profile 的 ModelForm 中包含该字段。

    相反,如果只有两个表单并将初始数据传递给包含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 之间共享逻辑。如果您需要配置文件实例数据,您可以随时将其传递到那里。

    我更喜欢这种方法,因为它不那么神奇,如果你在一年后回顾你的代码,你不会想知道为什么,在简短的扫描中,为什么 emailModelForm 的一部分,而它不是作为该模型上的一个字段存在。

    【讨论】:

    • 我同意你的观点,在模型表单中包含电子邮件字段确实没有意义。不过,在我的情况下,情况有点不同。另外,我只是在阅读inital 的文档,这对我来说似乎很有帮助。感谢您的回复:)
    • 酷,我只是在做假设,但如果它有帮助,那就太棒了!编码愉快。
    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多