views:

43

answers:

1

Hi all,

I'm trying to force a form field to be required based on a choice widget during validation.

def clean(self):
    cleaned_data = self.cleaned_data
    if cleaned_data.get('periodical') == True:
        if cleaned_data.get('period_start_date') == None:
            msg = _('custom message')
            self._errors['period_start_date'] = ErrorList([msg])

The code example works, but there's no distinction in error messages anymore between whether period_start_date is required (thus not empty) or whether it's a proper formatted date. Since Django's validation handles this properly I'm not looking to replace this.

What I'm trying to accomplish (sort of) is setting required to True on the period_start_date field when the choicefield 'periodical' is ticked just before it runs clean(). Anybody a enlightening tip for me?

Thanx.

+1  A: 
def clean_period_start_date(self):
  psd = self.cleaned_data['period_start_date']
  prd = self.cleaned_data['periodical']
  if prd:
    if not psd:
      raise forms.ValidationError("Start date is required on a periodical thing...")
  return psd

clean just the period start date. then you can raise the error specifically for that.

Brandon H
reading further in the docs, you can also raise the validationerror in your clean method that you already have. http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
Brandon H
Duh me .. never crossed my mind to do the clean_ on the psd. Only messed with it on prd .. thanx a lot!
GerardJP