Login

Swithched Value Typed Choice Field

Author:
I159
Posted:
November 16, 2011
Language:
Python
Version:
Not specified
Tags:
forms form_field
Score:
0 (after 0 ratings)

As it took me a save option name instead of its value. This field are solves this rare 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
class SwithchedValueTypedChoiceField(MultipleChoiceField):
    """
    Return selected data as value instead of value html ttribute.
    """        
    def to_python(self, value):        
        if not value:
            return []
        elif not isinstance(value, (list, tuple)):
            raise ValidationError(self.error_messages['invalid_list'])
        
        def switched(value, choices):
            """
            Switched value generator
            """
            count = 0
            max_count = len(value)
            while count < max_count:
                yield choices[value[count]]
                count += 1

        value = list(switched(value, dict(self._choices)))
        return value
        
    def valid_value(self, value):
        "Check to see if the provided value is a valid choice"
        for k, v in self.choices:
            if isinstance(v, (list, tuple)):
                # This is an optgroup, so look inside the group for options
                for k2, v2 in v:
                    if value == smart_unicode(v2):
                        return True
            else:
                if value == smart_unicode(v):
                    return True
        return False

More like this

  1. AutoSlugField and unique_slugify combined by Ciantic 5 years, 7 months ago
  2. template tag to get form field value by nmb10 4 years, 9 months ago
  3. Field value as plain text which can't be edited by user by szczavv 5 years, 11 months ago
  4. OrderField by zenx 5 years, 7 months ago
  5. CheckedField by oggy 6 years, 11 months ago

Comments

Please login first before commenting.