Why is Django giving me this "Violate non-null constraint" error?

Error:

The null value in the "postal_code_id" column violates a non-null constraint

The form:

def add(request):
    if request.method == 'POST':
        address_form = AddressForm(request.POST)
        company_form = CompanyForm(request.POST)
        if address_form.is_valid() and company_form.is_valid():
            print address_form.cleaned_data['postal_code'] # <-- prints (<PostalCode: V4N 1K6>, False)
            address_form.save() # <------------------------------- occurs here
        else:
            print 'Address errors',address_form.errors
            print 'Company errors', company_form.errors
    else:
        address_form = AddressForm()
        company_form = CompanyForm()
    return render(request, 'company/add.html', locals())

Obviously the form has a valid object PostalCode, so I'm not sure why it says it violates a non-null constraint. Of course I'm doing something funny with the form:

class AddressForm(ModelForm):
    postal_code = CharField(max_length=10, validators=[validate_postal_code])
    city = CharField(max_length=50, validators=[validate_non_whitespace])
    province = CharField(max_length=50, validators=[validate_non_whitespace])
    country = CharField(max_length=50, initial='Canada', validators=[validate_non_whitespace])

    def clean_postal_code(self):
        code = self.cleaned_data['postal_code']
        code = code.upper()
        code = re.sub('[^A-Z0-9]', '', code)
        code = code[:3] + ' ' + code[-3:]
        return code

    def clean_country(self):
        country = self.cleaned_data['country']

        try:
            country = Country.objects.get(name__iexact=country)
        except Country.DoesNotExist:
            raise ValidationError('Country does not exist')

        return country

    def clean_province(self):
        province = self.cleaned_data['province']

        if not Province.objects.filter(name__iexact=province).exists():
            raise ValidationError('Province does not exist')

        return province

    def clean(self):
        data = self.cleaned_data

        if 'country' in data and 'province' in data:
            try:
                data['province'] = Province.objects.get(country=data['country'], name__iexact=data['province'])
                if 'city' in data:
                    data['city'] = City.objects.get_or_create(name__iexact=data['city'], province=data['province'], defaults={'name':data['city']})[0]
                    if 'postal_code' in data:
                        data['postal_code'] = PostalCode.objects.get_or_create(code=data['postal_code'], city=data['city'])
            except Province.DoesNotExist:
                self._errors['province'] = self.error_class(['Province does not exist in that Country'])
                del data['province']

        return data

    class Meta:
        exclude = ['postal_code']
        model = Address

In particular, I replace the field with a postal_codetext field, and then I find / create an object in the "clean" method. Why does this confuse Django? He gets the object that he needs at the end, right?

+3
source share
4 answers

postal_code, , . , django, . , .

, postal_code , .

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

. .

Edit:

CharField ForeignKey ModelForm. . , , . , . , ModelForm, .

+2

Django, , , , , ?

+1

, uploaded_by , . ModelForm, uploaded_by. , fooobar.com/questions/471749/... .

+1

I came to this question since I was getting this IntegrityError error when I tried to send an instance of ModelForm that had CharField with blank=True(yep null=Trueshould never be used with CharField). The problem was in the form itself: the corresponding field method clean_field()first checked for the presence of the field value, but if the value did not exist, it returned the value None, and that is why the non-null constraint was violated. Fixing a method to return the same cleaned_data['field']one that was checked for value solved the problem.

0
source

All Articles