self.instance in Django ModelForm

Question:

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:
        ...
Asked By: jazzblue

||

Answers:

You can find the documentation on django’s website.

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method

Just search the page for every reference to “instance”, and you should find what you need.

# Load up an instance
my_poll = Poll.objects.get(id=1)

# Declare a ModelForm with the instance
my_form = PollForm(request.POST, instance=my_poll)

# save() will return the model_form.instance attr which is the same as the model passed in
my_form.save() == my_poll == my_form.instance
Answered By: Bryan

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.

Answered By: Fiver

For now we need to check with more accurate way as self.instance can’t be None (maybe old way checking still would work)
https://github.com/django/django/blob/65e03a424e82e157b4513cdebb500891f5c78363/django/forms/models.py#L302

    if self.instance.pk is not None: # or just if self.instance.pk

Try to print(self.instance, type(self.instance), self.instance.pk) and one can find that:
type is <class…> but self.instance is None

Answered By: Ivan Vinitskyi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.