在Django内联模型管理员中,如何使用值预填充额外的字段 [英] In django inline model admin, how to prefill extra fields with values
问题描述
class MyCustomInline(admin.TabularInline):
min_num = 1
extra = 0
fields = ['matcher', 'param0', 'param1']
model = MyModel
form = MyCustomInlineForm
def get_formset(self, request, obj=None, **kwargs):
extra_fields = {
'param0': forms.CharField(label='First Param', required=False),
'param1': forms.CharField(label='Second Param', required=False)
}
kwargs['form'] = type('MyCustomInline', (MyCustomInlineForm,), extra_fields)
return super(MyCustomInline, self).get_formset(request, obj, **kwargs)
这基本上就是我定义内联表单的方式,这样它就有两个额外的字段- matcher
是相关表中的标准字段,并且内联表单会自动处理它。然后,通过覆盖 MyCustomInlineForm
中的 save()
将额外的参数值保存在其他存储中。
This is basically how I define my inline form so that it has two extra fields - matcher
is a standard field in the related table and the inline form handles it automatically. And I save the extra param values in a different storage via overriding the save()
in MyCustomInlineForm
.
但是如果我编辑现有记录,匹配器值会正确显示,但显然我也想用相应的值预加载param0和param1。
But if I edit an existing record - matcher value appears correctly but I obviously also want to preload the param0 and param1 with the corresponding values. Where can I hook up to do that?
推荐答案
我设法自己做到了。我还设法简化了定义自定义额外字段的方式,而没有覆盖 get_formset
方法:
I managed to do it on my own. I also managed to simplify the way I define my custom extra fields, without overriding get_formset
method:
class MyCustomInlineForm(forms.ModelForm):
matcher = forms.ChoiceField(choices=[(v['name'], v['name']) for v in matchers], label='Matcher')
param0 = forms.CharField(label='First Param', required=False)
param1 = forms.CharField(label='Second Param', required=False)
def __init__(self, *args, **kwargs):
super(MyCustomInlineForm, self).__init__(*args, **kwargs)
if self.instance.pk:
""" self.instance is the model for the current row.
If there is a pk property that is not None, it means it's not
a new, empty inline model but we are working with existing one."""
self.initial['param0'], self.initial['param1'] = custom_way_to_load_params(self.instance)
def save(self, commit=True):
model = super(MyCustomInlineForm, self).save(True)
param0 = self.cleaned_data['param0']
param1 = self.cleaned_data['param1']
custom_way_to_save_params(model, param0, param1)
return model
class MyCustomInline(admin.TabularInline):
min_num = 1
extra = 0
fields = ['matcher', 'param0', 'param1']
model = MyModel
form = MyCustomInlineForm
如果需要-可以通过覆盖 forms.ModelForm 的
is_valid()
方法来完成自定义参数的验证。 code>类,并通过 self.add_error()
添加错误。我希望它能对某人有所帮助。
If needed - validation of custom params could be done by overriding is_valid()
method of forms.ModelForm
class and adding errors via self.add_error()
. I hope it helps someone.
这篇关于在Django内联模型管理员中,如何使用值预填充额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!