mercredi 13 août 2014

python - Django : impossible d'enregistrer champ de formulaire vide à la base de données - invalid literal pour int() avec base 10: ''-Stack Overflow


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.




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



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.



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


0 commentaires:

Enregistrer un commentaire