gpt4 book ai didi

django - 在 __init__ 处动态添加到 ModelForm 的字段不会保存

转载 作者:行者123 更新时间:2023-12-02 17:53:34 29 4
gpt4 key购买 nike

我正在使用 Django 配置文件,并受到 James Bennett 的启发,创建了一个动态表单 (http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/)

我需要的是一个公司字段,仅当 user_type 为“pro”时才显示在我的用户个人资料表单上。基本上我的模型和表单看起来像:

class UserProfile(models.Model):
user_type = models.CharField(...
company_name = models.CharField(...

class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
exclude = ('company_name',)

我在 init 中添加了 company_name 字段,就像 James Bennett 所展示的那样:

def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args,**kwargs)
if (self.instance.pk is None) or (self.instance.user_type == 'pro'):
self.fields['company_name'] = forms.CharField(...

问题是,当我尝试 save() UserProfileForm 的实例时,字段“company_name”未保存...

我通过在 save() 方法中显式调用该字段来解决这个问题:

def save(self, commit=True):
upf = super(UserProfileForm, self).save(commit=False)
if 'company_name' in self.fields:
upf.company_name = self.cleaned_data['company_name']
if commit:
upf.save()
return upf

但我对这个解决方案并不满意(如果有更多字段怎么办?Django 的美丽怎么样?等等)。它让我彻夜难眠,试图让模型表单了解 init 处的新 company_name 字段。

这就是我如何最终在 stackoverflow 上发布此内容的故事......

最佳答案

我会从表单中删除此逻辑并将其移至工厂。如果你的逻辑在工厂中,你可以有两种形式:

  • 用户配置文件表单
  • ProUserProfileForm

ProUserProfileForm 继承自 UserProfileForm,仅更改“排除”常量。

您将拥有以下工厂:

def user_profile_form_factory(*args, instance=None, **kwargs):
if (self.instance.pk is None) or (self.instance.user_type == 'pro'):
cls = ProUserProfileForm
else:
cls = UserProfileForm
return cls(*args, instance, **kwargs)

关于django - 在 __init__ 处动态添加到 ModelForm 的字段不会保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4773463/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com