Django Charfield null=False Inegrity Error not raised
<p>I have a model:</p>

<pre><code>class Discount(models.Model):
    code = models.CharField(max_length=14, unique=True, null=False, blank=False)
    email = models.EmailField(unique=True)
    discount = models.IntegerField(default=10)
</code></pre>

<p>In my shell when I try and save a Discount object with no input, it doesn't raise an error. What am I doing wrong?</p>

<pre><code>&gt; e = Discount()
&gt; e.save()
</code></pre>

<p>No default Django behavior will save <code>CHAR</code> or <code>TEXT</code> types as <code>Null</code> - it will always use an empty string (<code>''</code>). <code>null=False</code> has no effect on these types of fields. </p>

<p><code>blank=False</code> means that the field will be required by default when the model is used to render a ModelForm. It does not prevent you from manually saving a model instance without that value.</p>

<p>What you want here is a custom model validator:</p>

<pre><code>from django.core.exceptions import ValidationError
def validate_not_empty(value):
    if value == '':
        raise ValidationError('%(value)s is empty!'), params={'value':value})
</code></pre>

<p>Then add the validator to your model:</p>

<pre><code>code = models.CharField(max_length=14, unique=True, validators=[validate_not_empty])
</code></pre>

<p>This will take care of the form validation you want, but validators don't automatically run when a model instance is saved. <a href="https://docs.djangoproject.com/en/1.10/ref/validators/#how-validators-are-run" rel="nofollow">Further reading here.</a> If you want to validate this every time an instance is saved, I suggest overriding the default <code>save</code> behavior, checking the value of your string there, and interrupting the save by raising an error if necessary. <a href="http://stackoverflow.com/questions/9953427/django-custom-save-model">Good post on overriding <code>save</code> here.</a></p>

<p><a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#null" rel="nofollow">Further reading on <code>null</code>:</a> </p>

<blockquote>
  <p>Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for âno dataâ: NULL, and the empty string. In most cases, itâs redundant to have two possible values for âno data;â the Django convention is to use the empty string, not NULL.</p>
</blockquote>

<p><a href="https://docs.djangoproject.com/en/1.10/ref/validators/" rel="nofollow">And on validators.</a></p>

python django django-models