3
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.

0

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

6 Comments

Ok, but I have a problem, I don't know what to substitute instead of ???? form = ProductAdminForm(instance=????)
you don't have to specify it. By default the instance is the Product currently edited (no instance if creation)
But Django throws KeyError exception for 'created' and 'instance'
Now I don't have this error, but self.instance.id, self.instance.price and others fields is None. I try to edit object, not to create, so it's strange that all is None.
Well, it works on my current project on edit. except I don't have the request parameter on my init, try remove it. and you must have class Meta: model = Product added on the ProductAdminForm definition as in my re-edited post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.