如何将字段的初始值传递给模型表单。我有类似下面的代码
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类字段的初始值。我怎么能这样做?
答案 0 :(得分:10)
您可以将初始值传递给ModelForm,如下所示:
form = PersonForm(initial={'fieldname': value})
例如,如果您想将初始age
设置为24
而将name
设置为"John Doe"
:
form = PersonForm(initial={'age': 24, 'name': 'John Doe'})
我认为这可以解决您的实际问题:
def my_form_factory(user_object):
class PersonForm(forms.ModelForm):
# however you define your form field, you can pass the initial here
log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object)
...
return PersonForm
class PersonAdmin(admin.ModelAdmin):
form = my_form_factory(get_current_user())
答案 1 :(得分:7)
由于您的ModelForm绑定到Person-Model,您可以传递Person-Instance:
form = PersonForm(instance=Person.objects.get(foo=bar)
或覆盖ModelForm的init-method:
class PersonForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['foo'].value = 'bar'
class Meta:
model = Person
exclude = ['name']
这是未经测试的。我不确定“值”是否正确,我在这里没有Django-Installation,但基本上这就是它的工作方式。
答案 2 :(得分:7)
如果有人还在想,以下方法可以设置管理员表单的初始值:
class PersonAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(PersonAdmin, self).get_form(request, obj=obj, **kwargs)
form.base_fields['log_user'].initial = get_current_user()
return form
请注意,您还可以通过网址参数设置初始值:例如 /管理/人/加?LOG_USER =我的