Django error while saving Foreign Key - Can not assign none , Doesn't allow null values
<p>I have two models - Events and Tenants. </p>

<pre><code>class EventsModel(models.Model):
    sys_id = models.AutoField(primary_key=True, null=False, blank=True)
    tenant_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.CASCADE, null=False, blank=True)
    name = models.CharField(max_length=80, null=False, blank=False)
    start_date_time = models.DateTimeField(null=False, blank=False)
    end_date_time = models.DateTimeField(null=False, blank=False) 
    created_when = models.DateTimeField(null=False, blank=True)   

    def save(self, *args, **kwargs):
        self.created_when = timezone.now()
        self.tenant_sys_id = 1 #for-testing-only. actual current_logged_in_user.tenant_sys_id
        return super(EventsModel, self).save(*args, **kwargs)
</code></pre>

<p>This model have a FK tenant_sys_id to tenant model. If for this I set null = False then below error is thrown.</p>

<pre><code>ValueError('Cannot assign None: "EventsModel.tenant_sys_id" does not allow null values.',)  
</code></pre>

<p>I am setting the value of this field in overridden save method from the logged in user details.
Setting null = True doesn't throw this error.</p>

<p>However is I do the same for created_when field this behavior is not shown. Irrespective of null=True/False, value is being set from save method and saved.</p>

<p>I am getting this error in View File.</p>

<pre><code>form = EventsForm(request.POST)
print(request.POST) # print
print(form) # do not print. error here &lt;--
if form.is_valid(): # error here if above line is commented.
    form.save()
</code></pre>

<p>ModelForm class</p>

<pre><code>class EventsForm(ModelForm):
    class Meta:
        model = EventsModel
        fields = '__all__'
</code></pre>

<p>So here I am not able to understand -<br>
1. why I must set FK to null=True and not created_when in order to work.<br>
2. Why it is throwing error while creating form and not while saving data.</p>

<p><strong>Update</strong>:
Anybody downvoting the question - Please atleast mention the reason in comments about why you think this question is not asked in a proper way?</p>

<p>Your ForeignKey should be called <code>tenant_sys</code>, not <code>tenant_sys_id</code>. Django will automatically add the <code>_id</code> suffix to the underlying database field, but the value you have in Python is actually an instance of the target model, not an ID.</p>

<p>With the code you have, you are still not setting the db value; you set the object, which Django will actually convert into <code>tenant_sys_id_id</code>, but the db column remains empty, hence the integrity error. The reason why there is no form validation error is because you also have <code>blank=True</code> on the field definition.</p>

python django django-models foreign-keys