Prevent initializing model form when creating
<p>In a Django form, I encountered a strange python behavior. I have a model form which I want to populate with some existing data. Because one field is meant to be a comma separated list of an m2m field I have to initialize it separately.</p>

<pre><code>class SomeModel(models.Model):
    confirming_stuff = models.ManyToManyField(OtherModel,related_name='confirming')

    def get_confirming(self):
    return ','.join([l.pmid for l in self.confirming_stuff.all()])

 class SomeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        self.initial['confirming_field'] = self.instance.get_confirming()
</code></pre>

<p>Everything works fine with an update. The field is populated with comma separated entries as expected. The problem arises with creation. As the instance does not yet exist the field cannot be filled with data, so I tried to skip this step. But it doesn't work. Instead, I encountered a strange behavior of the python code.</p>

<pre><code>class SomeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        if self.instance:
            print "Self instance: ",self.instance
            self.initial['some_field'] = self.instance.get_some_field()
</code></pre>

<p>produces the same error. Additionally the printout on the debug screen shows:</p>

<blockquote>
  <p>Self instance: None</p>
</blockquote>

<p>I tried several other logical expressions, </p>

<pre><code>if self.instance != None:
if not self.instance == None:
if self.instance &gt; 0:
</code></pre>

<p>but the result remains the same.</p>

<p>It remains a mystery to me why the instance is printed as 'None' but cannot be tested properly as such. </p>

<p>You will always have an <code>instance</code> object, just check if its saved.</p>

<pre><code>if self.instance.id:
    #do stuff
</code></pre>

<p>Thanks.</p>

python django initialization modelform