Login

PartialRequiredMultiValueField

Author:
hvdklauw
Posted:
December 7, 2009
Language:
Python
Version:
1.1
Tags:
form multivaluefield
Score:
0 (after 0 ratings)

Allows the whole widget to be required but still have optional fields in it.

For instance we have a NameField, which takes a firstname and lastname and optionally a middlename.

With this we can just have 1 widget.

 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
45
46
47
48
49
50
51
52
53
54
55
from django.forms.fields import MultiValueField, EMPTY_VALUES
from django.forms.util import ErrorList

class PartialRequiredMultiValueField(MultiValueField):
    """
        Overwrites the default django multivalue field.
        Instead of checking the required for ALL fields we don't throw errors
    """
    
    fields_required = []
    
    def __init__(self, fields=(), *args, **kwargs):
        for f in fields:
            self.fields_required.append(bool(f.required))
        self.fields = fields
        super(MultiValueField, self).__init__(fields, *args, **kwargs)
        
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        
        Added the field specific required check
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in EMPTY_VALUES]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages['invalid'])
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if self.required and field_value in EMPTY_VALUES and self.fields_required[i]:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError, e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)
        return self.compress(clean_data)

More like this

  1. Allow disabling options in a select widget by scjody 3 years, 11 months ago
  2. Allow disabling options in a checkboxselectmultiple widget by sterkh 2 years, 10 months ago
  3. Choice Field and Select Widget With Optional Optgroups by leahculver 8 years, 1 month ago
  4. SelectDateWidget by silent1mezzo 4 years, 5 months ago
  5. Dynamically add css-classes to formfields by Lacour 3 years, 10 months ago

Comments

Please login first before commenting.