[Django]-Why is Django giving me this "violates not-null constraint" error?


You’re excluding postal_code, which will cause the model form to skip over the field later on during the save attempt. I’ve had a similar problem, and had to trace through django code to figure out the behaviour. It’s worth doing by the way.

What you want to do instead, is set the widget used for the postal_code field instead of excluding then including.

class AddressForm(ModelForm):
    class Meta:
        model = Address
        widgets = {
            'postal_code': CharField(max_length=10),

That should allow the modelform to validate the field correctly and save it. I excluded the rest of your form for brevity.


Attempting to use a CharField for a ForeignKey is fraught with horrible in a ModelForm. Instead, convert it to a regular form. You already appear to be defining most of your fields anyway. Then the reliance is on you to validate that fields are valid, and are members of the database already. Create a save method that behaves like the ModelForm save method, and away you go.


I don’t know Django, but perhaps you have to make sure that the postal code is saved before you try to save the address?


I came to this question because I was trying to automatically add an uploaded_by field to form data before the form was saved. I was using a ModelForm, with uploaded_by excluded. I found that the answer to a related stackoverflow question was a succinct solution to this problem.



I arrived at this question since I was getting that IntegrityError error when I tried to submit a ModelForm instance which had a CharField with blank=True (yep, null=True should never be used with CharField). The problem was in the form itself: the respective field’s clean_field() method was checking for existence of the field’s value first, but if the value did not exist, it returned None, which is exactly why not-null constraint was violated. Fixing the method to return the same cleaned_data['field'] that was checked for a value solved the problem.

Leave a comment