Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6031109
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T05:08:07+00:00 2026-05-23T05:08:07+00:00

The error: null value in column postal_code_id violates not-null constraint The form: def add(request):

  • 0

The error:

null value in column “postal_code_id” violates not-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())

Clearly the form does have a valid PostalCode object, so I’m not sure why it’s saying it violates the not-null constraint. Of course, I am doing something kinda 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

Specifically, I’m replacing the postal_code field with a text field and then I find/create the object in the “clean” method. Why does that confuse Django? It’s getting the object it needs in the end, isn’t it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T05:08:07+00:00Added an answer on May 23, 2026 at 5:08 am

    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.

    Edit:

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I get this message when compiling C++ on gcc 4.3 error: ‘NULL’ was not
Through the front end I want to insert NULL value to the Column whose
I am trying to add NOT NULL and a DEFAULT to an existing table.
I'm having a document.body is null error in my javascript because I use: $(window).width()
What causes the FAIL - Deploy Upload Failed, Exception: null error message in tomcat?
I got RJS error: TypeError: element is null while using ajax. I used in
I get the following error on firebug: this._processor is null and the error is
The following code is throwing the error this.element is null. However, the wid_cont is
Here is my error: Warning: mysql_query() expects parameter 2 to be resource, null given...
[hannel,192.168.0.46:40014] 15:08:03,642 - ERROR - org.jgroups.protocols.UDP - failed sending message to null (61 bytes)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.