Django form validation on empty IntegerField

I have a form that I am not processing as part of an HTML page, but validating the input:

class milestone_form(forms.Form):
    name = forms.CharField(required=True)
    completion = forms.IntegerField(initial=0, required=False)
    due_date = forms.DateField(required=True,input_formats={'%d.%m.%Y'})
    phase = forms.IntegerField(required=True)


this completion bit causes a lot of problems:

form = milestone_form(request.POST)
form.is_valid()#will return False on empty completion


I tried overriding the clean () form to make completion = 0 when empty:

def clean(self):
    cleaned_data = self.cleaned_data
    if cleaned_data.get('completion') is None:
        cleaned_data['completion'] = 0
    return cleaned_data 


However, this does not help. Is there something else I am missing?


source to share

1 answer

Most likely I will fall back to returning an integer for an empty field with error checking:

from django.forms import ValidationError

def clean_completion(self):
    if self.cleaned_data.get('completion'):
            return int(self.cleaned_data['completion'].strip())
        except ValueError:
            raise ValidationError("Invalid number")
    return 0




All Articles