Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self.instance in Django ModelForm

Tags:

python

django

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:         ... 
like image 782
jazzblue Avatar asked Aug 16 '13 02:08

jazzblue


People also ask

What is self instance in Django?

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.

What is ModelForm in Django?

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.

What is def __ str __( self Django?

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.

What is the purpose of __ Str__ method in Django?

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.


1 Answers

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.

like image 93
Fiver Avatar answered Sep 20 '22 11:09

Fiver