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']
address_form.save()
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?
source
share