Login

clean validation for dynamic form fields

Author:
leveillej
Posted:
May 18, 2010
Language:
Python
Version:
1.2
Tags:
forms validation dynamic-forms
Score:
0 (after 0 ratings)

I needed a way to validate non-required, dynamically generated form fields, and clean provided the best solution for this problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django import forms
from openair.estimate.models import MyModel

MAX_LEG_FORMS = 5

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        for i in range(0, MAX_LEG_FORMS):
            self.fields['leg_location_%s' % i] = forms.CharField(
                label=u'Location',
                max_length=50,
                required=False
            )
            self.fields['leg_airport_%s' % i] = forms.RegexField(
                label=u'Departure Airport',
                max_length=3,
                min_length=3,
                regex=r'^[a-zA-Z0-9]{3}$',
                required=False
            )
            self.fields['leg_delay_%s' % i] = forms.IntegerField(
                label=u'Delay (in hours)',
                min_value=0,
                initial=0,
                required=False
            )

    def clean(self):
        cleaned_data = self.cleaned_data
        for i in range(1, MAX_LEG_FORMS):
            location = cleaned_data.get("leg_location_%s" % i)
            airport = cleaned_data.get("leg_airport_%s" % i)
            delay = cleaned_data.get("leg_delay_%s" % i)
            if location != '' and airport in ['', False, None]:
                airport_msg = 'Validation message here'
                self._errors["leg_airport_%s" % i] = self.error_class([airport_msg])
            if location != '' and delay in ['', False, None]:
                delay_msg = 'Validation message here'
                self._errors["leg_delay_%s" % i] = self.error_class([delay_msg])
        return cleaned_data

    class Meta:
        model = MyModel

More like this

  1. newforms: Add field-specific error in form.clean() by miracle2k 7 years, 10 months ago
  2. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 7 years, 10 months ago
  3. UKPhoneNumberField by nathan-reynolds 6 years, 6 months ago
  4. UKPhoneNumberField GB v2 by g1smd 2 years, 8 months ago
  5. Automatically trim newforms text fields by miracle2k 7 years, 8 months ago

Comments

Please login first before commenting.