Django 为与继承模型关联的ModelForm指定初始字段值
问题:如果使用模型继承,并且在呈现Django 为与继承模型关联的ModelForm指定初始字段值,django,django-forms,model-inheritance,Django,Django Forms,Model Inheritance,问题:如果使用模型继承,并且在呈现模型表单时,每个子模型需要具有不同的默认值,那么建议如何为字段指定初始值 以以下模型为例,CompileCommand和TestCommand在呈现为ModelForm时都需要不同的初始值 # ------ models.py class ShellCommand(models.Model): command = models.Charfield(_("command"), max_length=100) arguments = models
模型表单
时,每个子模型需要具有不同的默认值,那么建议如何为字段指定初始值
以以下模型为例,CompileCommand
和TestCommand
在呈现为ModelForm
时都需要不同的初始值
# ------ models.py
class ShellCommand(models.Model):
command = models.Charfield(_("command"), max_length=100)
arguments = models.Charfield(_("arguments"), max_length=100)
class CompileCommand(ShellCommand):
# ... default command should be "make"
class TestCommand(ShellCommand):
# ... default: command = "make", arguments = "test"
我知道在实例化表单时可以使用initial={…}
参数,但是我更愿意将初始值存储在模型的上下文中(或者至少存储在关联的ModelForm中)
我目前的做法
我现在正在做的是在Meta
中存储一个初始值dict,并在我的视图中检查它
# ----- forms.py
class CompileCommandForm(forms.ModelForm):
class Meta:
model = CompileCommand
initial_values = {"command":"make"}
class TestCommandForm(forms.ModelForm):
class Meta:
model = TestCommand
initial_values = {"command":"make", "arguments":"test"}
# ------ in views
FORM_LOOKUP = { "compile": CompileCommandFomr, "test": TestCommandForm }
CmdForm = FORM_LOOKUP.get(command_type, None)
# ...
initial = getattr(CmdForm, "initial_values", {})
form = CmdForm(initial=initial)
这感觉太像黑客了。我渴望找到一种更通用/更好的方法来实现这一点。欢迎提出建议
更新的解决方案(看起来很有希望)
我现在在forms.py
中有以下内容,允许我在视图中设置Meta.default\u initial\u值,而不需要额外的样板代码。如果用户未指定initial={…}
args,则使用默认值
class ModelFormWithDefaults(forms.ModelForm):
def __init__(self, *args, **kwargs):
if hasattr(self.Meta, "default_initial_values"):
kwargs.setdefault("initial", self.Meta.default_initial_values)
super(ModelFormWithDefaults, self).__init__(*args, **kwargs)
class TestCommandForm(ModelFormWithDefaults):
class Meta:
model = TestCommand
default_initial_values = {"command":"make", "arguments":"test"}
如果必须发送到表单init,那么在表单的meta上设置初始值没有多大用处
我宁愿创建一个覆盖构造函数方法的ModelForm子类,然后将该子类用作其他表单的父类
e、 g
您是否尝试覆盖构造函数并设置新的默认值/init值?我很幸运地覆盖了模型。\uuuu init\uuuu()
(但是),而覆盖每个模型表单的构造函数将得到比我目前拥有的代码更为丰富的代码。更新了问题以显示我所做的尝试。关于您的编辑,我认为您必须检查kwargs.get('data')是否为None,然后执行self.fields[“command”]。initial=“make”同意。这和我在闲逛之后得到的结果差不多。更新了问题以显示解决方案。
class InitialModelForm(forms.ModelForm):
#here you override the constructor
pass
class TestCommandForm(InitialModelForm):
#form meta
class CompileCommandForm(InitialModelForm):
#form meta