Source

django-members / members / forms.py

from django import forms


class SearchForm(forms.Form):
    search = forms.CharField(required=False)
    letter = forms.CharField(required=False, widget=forms.HiddenInput())
    
    def clean_letter(self):
        letter = self.cleaned_data['letter']
        if letter and not ord(letter) in range(ord('A'), ord('Z') + 1):
            raise forms.ValidationError('Not a valid letter')
        return letter


FIELDS = ('first_name', 'last_name', 'email', 'membership_type')
FIELD_MAP = {
    'first_name': ('contact', 'first_name'),
    'last_name': ('contact', 'last_name'),
    'email': ('contact', 'email'),
    'membership_type': ('membership', 'type'),
}

class ColumnMatchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        count = kwargs.pop('column_count')
        choices = [(i + 1, 'Column %d' % (i + 1)) for i in range(count)]
        choices.insert(0, ('', '------'))
        super(ColumnMatchForm, self).__init__(*args, **kwargs)
        for field in FIELDS:
            self.fields[field] = forms.ChoiceField(
                choices=choices,
                required=False,
            )
    
    def save(self):
        columns = []
        for key in FIELDS:
            if key in self.cleaned_data and self.cleaned_data[key] != '':
                index = int(self.cleaned_data[key]) - 1
                columns.append((FIELD_MAP[key], index))
        return columns