将初始值传递给 django 中的模型表单
如何将字段的初始值传递给模型表单。我有类似下面的代码
class ScreeningForm(forms.ModelForm):
class Meta:
model = Screening
def __init__(self, *args, **kwargs):
super(ScreeningForm, self).__init__(*args, **kwargs)
self.fields['blood_screen_type'] = CommaSeparatedCharField(
label=self.fields['blood_screen_type'].label,
initial=self.fields['blood_screen_type'].initial,
required=False,
widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
)
class ScreeningAdmin(admin.ModelAdmin):
#form = ScreeningForm
form = ScreeningForm(initial={'log_user':get_current_user()})
现在我想传递 Person 类的字段的初始值。我怎样才能做到这一点?
How can I pass an initial value for a field to a model form. I have something like the following code
class ScreeningForm(forms.ModelForm):
class Meta:
model = Screening
def __init__(self, *args, **kwargs):
super(ScreeningForm, self).__init__(*args, **kwargs)
self.fields['blood_screen_type'] = CommaSeparatedCharField(
label=self.fields['blood_screen_type'].label,
initial=self.fields['blood_screen_type'].initial,
required=False,
widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
)
class ScreeningAdmin(admin.ModelAdmin):
#form = ScreeningForm
form = ScreeningForm(initial={'log_user':get_current_user()})
Now I want to pass an initial value for a field of the Person class. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将初始值传递给 ModelForm,如下所示:
例如,如果您想将初始
age
设置为24
,将name
设置为“John Doe”
:更新
我认为这解决了您的实际问题:
You can pass initial value to a ModelForm like this:
For example, if you wanted to set initial
age
to24
andname
to"John Doe"
:Update
I think this addresses your actual question:
如果有人仍然想知道,可以通过以下方法为管理表单设置初始值:
请注意,您还可以通过 URL 参数设置初始值:例如 /admin/person/add?log_user=me
In case anyone is still wondering, the following works to set initial values for an Admin form:
Note that you can also set initial values via URL parameters: e.g. /admin/person/add?log_user=me
由于您的 ModelForm 绑定到 Person-Model,您可以传递 Person-Instance:
或覆盖 ModelForm 的 init-method:
这是未经测试的。我不确定“值”是否正确,我这里没有 Django 安装,但基本上这就是它的工作方式。
As your ModelForm is bound to the Person-Model, you could either pass a Person-Instance:
or overwrite the ModelForm's init-method:
This is untested. I'm not sure whether "value" is correct, I'm not having a Django-Installation here, but basically this is the way it works.