编程语言
首页 > 编程语言> > python-在Django内联模型管理员中,如何使用值预填充额外的字段

python-在Django内联模型管理员中,如何使用值预填充额外的字段

作者:互联网

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)

基本上,这就是我定义内联表单的方式,因此它具有两个额外的字段-匹配器是相关表中的标准字段,内联表单会自动处理它.然后,通过覆盖MyCustomInlineForm中的save()将额外的param值保存在其他存储中.

但是,如果我编辑一个现有记录-匹配器值正确显示,但我显然也想用相应的值预加载param0和param1.我在哪里可以挂接呢?

解决方法:

我设法自己做.我还设法简化了定义自定义额外字段的方式,而没有覆盖get_formset方法:

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

如果需要-可以通过重写form.ModelForm类的is_valid()方法并通过self.add_error()添加错误来验证自定义参数.希望对您有所帮助.

标签:django-admin,python,django
来源: https://codeday.me/bug/20191119/2032516.html