> # Assume these are key-value pairs > AGE_CHOICES=( > (1, '0-3'), > (2, '3-6'), > (3, '6-15'), > ) > > class CustomForm(forms.Form): > age = forms.ChoiceField(label='Age', choices=AGE_CHOICES) > > How can I get the value (not the key) of the age attribute after validation? > > if f.is_valid(): > cd = f.cleaned_data > > cd['age'] # returns the "key", not the value
Given that your choices are linear starting with one, you can do something like AGE_CHOICES[int(cd['age'])-1] For the more general case you'd want to create a dict() to do the mapping for you, but you need to insure the key is of the same type (int vs. string). I have the following pattern in my code quite a bit: FOO_A = 'a' FOO_B = 'b' FOO_C = 'c' FOO_CHOICES = { FOO_A: 'This is A", FOO_B: 'This is B's description", FOO_C: 'This is my C", } class MyModel(Model): foo = CharField(..., choices = FOO_CHOICES.items()) : : foo = my_form.cleaned_data['foo'] my_foo_desc = FOO_CHOICES.[foo] If order matters, you can use choices=sorted(FOO_CHOICES.items()) or choices=sorted(FOO_CHOICES.items(), key=lambda x:x[1]) as your "choices" clause to sort them (the first by key, the second by value), as dicts aren't guaranteed to be ordered. Hope this helps, -tim --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---