访问表单中的管理模型实例

时间:2021-10-02 15:53:03
class ProductAdmin(admin.ModelAdmin):
    form = ProductAdminForm()

class ProductAdminForm(forms.ModelForm): 
    def __init__(self, request, *args, **kwargs):
         super(ProductAdminForm, self).__init__(*args, **kwargs)
         self.fields['field1'] = forms.CharField(required=False)
         self.fields['field2'] = forms.IntegerField()

How can I pass product instance from ProductAdmin to ProductAdminForm? I want to provide different fields depending of products instances.

如何将产品实例从ProductAdmin传递到ProductAdminForm?我想根据产品实例提供不同的字段。

1 个解决方案

#1


2  

this:

这样的:

class ProductAdminForm(forms.ModelForm):
     class Meta:
         model = Product

     def __init__(self, *args, **kwargs):
         super(ProductAdminForm, self).__init__(*args, **kwargs)

             product_instance = self.instance
             if product_instance.id and product_instance.myField == "thatValue":
                 self.fields['field1'] = forms.CharField(required=False)
                 self.fields['field2'] = forms.IntegerField()

#1


2  

this:

这样的:

class ProductAdminForm(forms.ModelForm):
     class Meta:
         model = Product

     def __init__(self, *args, **kwargs):
         super(ProductAdminForm, self).__init__(*args, **kwargs)

             product_instance = self.instance
             if product_instance.id and product_instance.myField == "thatValue":
                 self.fields['field1'] = forms.CharField(required=False)
                 self.fields['field2'] = forms.IntegerField()