ValueError: Field 'maca' expected a number but got ''. Django error

Viewed 34

I have a model like this

class Product(models.Model):

   class Maca(models.IntegerChoices):
       Yes = 1,
       No = 2,

   maca = models.PositiveSmallIntegerField(
       db_column='maca', choices=Maca.choices
   )

and a form like this

class ProductForm(forms.ModelForm):
   maca = forms.ChoiceField(required=False, choices=Product.Maca.choices, widget=forms.RadioSelect())

I have one case that this field will not show on the form.

But when it is not in the form, the field 'maca' will submitted as '' (Blankn) and I'm getting an error for this

ValueError: Field 'maca' expected a number but got ''.

Can someone help me please? How can I send this in database as None value?

1 Answers

A ModelForm field can be considered required or not required depending on the arguments of the fields in the model just as stated in the doc.

If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.

I'd suggest you restructure your code this way.

app/models.py

class Product(models.Model):

   class Maca(models.IntegerChoices):
       Yes = 1,
       No = 2,

   maca = models.PositiveSmallIntegerField(
       db_column='maca', choices=Maca.choices, blank=True, null=True
   )

app/forms.py

class ProductForm(forms.ModelForm):
   maca = forms.ChoiceField(choices=Product.Maca.choices, widget=forms.RadioSelect())

A ModelForm field is considered not required when it has blank=True,

blank, and null arguments are False by default.

Related