What does self.instance in Django ModelForm constructor mean and where can I find a documentation about it?
class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) if self.instance: ...
instance is derived from the model attribute specified in the Meta class. Your self in this context is obviously an instance of your subclass of ModelForm, and self. instance is (and will be on saving the form without errors) an instance of the model class you specified, although you have not done so in your example.
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.
In a ModelForm, self.instance is derived from the model
attribute specified in the Meta class. Your self
in this context is obviously an instance of your subclass of ModelForm, and self.instance is (and will be on saving the form without errors) an instance of the model class you specified, although you have not done so in your example.
Accessing self.instance in __init__
may not work, though doing so after calling the parent's __init__
probably will. Further, I wouldn't recommend trying to change the instance directly. If you are interested, have a look at the BaseModelForm code on Github. The instance
can also be specified when creating a new form via the instance
argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With