abolotnov
abolotnov

Reputation: 4332

Django form validation on empty IntegerField

I have a form that I don't render as part of HTML page but validate input against:

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 is causing lots of problems:

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

I tried overriding form's clean() to make completion = 0 when it's empty:

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

However, it doesn't help. Is there something else I'm missing?

Upvotes: 3

Views: 6135

Answers (1)

Jeffrey Bauer
Jeffrey Bauer

Reputation: 14090

This is probably the way I'd go about returning an integer for a blank field, with error checking:

from django.forms import ValidationError

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

Upvotes: 3

Related Questions