forms.IntegerField with empty value allowed

Hi,
I am trying to create several input fields with forms.IntegerField. I want to make the fields optional, i.e. the fields can be left blank, for example, the “J” and “N” fields in the screenshot. Could someone please suggest how to do it?

Thanks so much in advance!

By default they show up blank in my test system.

Please post the form and the template being used here. If this is a ModelForm, please post the model as well.

Hi, thanks for your reply!

I defined the form as follows:

In the template:

    <label>J=</label>{{J_integer_field_initial}} (if applies)
    <label>N=</label>{{N_integer_field_initial}} (if applies)

In forms.py:

class VIntegerField(forms.Form):
    v = forms.IntegerField(
        label="",
        min_value = 0,
        max_value = 100,
    )
class JIntegerField(forms.Form):
    J = forms.IntegerField(
        label="",
    )

In views.py:

if request.method == "POST":
        J_integer_field_initial = JIntegerField(request.POST,prefix="J_integer_field_initial")
        J_integer_field_final = JIntegerField(request.POST,prefix="J_integer_field_final")
        N_integer_field_initial = JIntegerField(request.POST,prefix="N_integer_field_initial")
        N_integer_field_final = JIntegerField(request.POST,prefix="N_integer_field_final")

When I press the button to submit the form, it saids “Please fill out this field”. It seems like I can not set “blank=True” when defining the integerField.

image

The blank=True option is for ModelForm fields. You want to set required=False for these fields.

Side note: I find it highly unusual that you are creating one field per form. It seems like you’re creating a lot of excess work for yourself in this situation.

Hi Ken,

thanks so much for your help!

Could you please suggest what you would do to avoid creating one field per form?

Thanks again!

Yes, create one form for all your fields.

I see, thanks so much for your help!