Login

clean validation for dynamic form fields

Author:
leveillej
Posted:
May 18, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 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. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.