Dominic Comtois
Dominic Comtois

Reputation: 10411

Django: Can't save empty form field to database - invalid literal for int() with base 10: ''

Many people report this type of error, but so far none of the fixes worked for me. I have a model that has an IntegerField allowing for null values:

def SomeModel(models.Model):
    ...
    price_sell = models.IntegerField(null=True)
    ...

Then I have a form that goes like this:

class SomeForm(forms.Form):
    ...
    price_sell = forms.IntegerField(required=False)
    ...

When leaving this field empty, and calling the save method, I get a invalid literal for int() with base 10: '' error. I tried many things having to do with the blank and null parameters, but no luck so far.

My solution has been to do this is my views.py:

if form.is_valid():
    if(request.POST['price_sell'] == ''):
        price_sell = None
    ...

But I am certain there is a more elegant way to do this. Or is there not?

I'm running Django 1.6 on Windows with SQLite db.

Upvotes: 3

Views: 761

Answers (1)

Sam Dolan
Sam Dolan

Reputation: 32532

Grab the data from the cleaned_data in the form. The IntegerField will get you what you want. form.cleaned_data['price_sell']

Upvotes: 2

Related Questions