0

What self.instance means in the code below?

Class ProfileForm(forms.ModelForm):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
interest_0 = forms.CharField(required=True)
interest_1 = forms.CharField(required=True)
interest_2 = forms.CharField(required=True)

def save(self):
    Profile = self.instance
    Profile.first_name = self.cleaned_data[“first_name”]
    Profile.last_name = self.cleaned_data[“last_name”]

    profile.interest_set.all().delete()
    For i in range(3):
       interest = self.cleaned_data[“interest_{}”.format(i]
       ProfileInterest.objects.create(
           profile=profile, interest=interest)

Here is a complete code. I already read this post, but still, I can't understand their explanation. Can you explain in the easiest way possible?

Darkhan10
  • 79
  • 6

1 Answers1

0

The .instance attribute is the model object that the form is constructing or 8editing*. In this case it is (likely) a Profile object.

When you create a ProfileForm, you can pass an instance, like:

ProfileForm(request.POST, instance=some_profile)

If you do not pass a instance=… parameter, then the form will construct a new Profile object. If you thus save the instance, then it will thus create a corresponding record in the database.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555