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

时间:2011-07-21 14:06:49

标签: django django-admin django-forms

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?我想根据产品实例提供不同的字段。

1 个答案:

答案 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()