如何在Django管理员中为模型字段使用自定义表单字段?

时间:2023-01-14 19:36:26

I want to have the Django admin use a custom form field for the input of some fields.

我想让Django管理员使用自定义表单字段来输入某些字段。

Until now I made a custom model field that has the form field bound to it which works great but it introduces an unecessary model field that does not add any benefit.

到目前为止,我创建了一个自定义模型字段,其中包含绑定到它的表单字段,但它引入了一个不必要的模型字段,但不会增加任何好处。

I guess it can be done somehow using a custom admin form (see http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin) but I couldn't figure out how to do it.

我想可以使用自定义管理表单以某种方式完成(请参阅http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin)但我不能弄清楚该怎么做。

1 个解决方案

#1


8  

class MyModelForm(forms.ModelForm):
    my_field = MyCustomFormField()

    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

#1


8  

class MyModelForm(forms.ModelForm):
    my_field = MyCustomFormField()

    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm