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()
如何将产品实例从ProductAdmin传递到ProductAdminForm?我想根据产品实例提供不同的字段。
答案 0 :(得分:2)
这样:
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()