Login

Choices

Author:
cronosa
Posted:
January 7, 2010
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

This allows you to access the choices (and their respective values) you create as a dictionary. It works great within django and it allows you to reference the choices as a dictionary (CHOICES[CHOICE1]) instead of CHOICES[0][0]... it is a tuple... but I mean, come on... what if you change the order? If you need the tuple just call CHOICES.choices and it will return the standard tuple.

 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
from django.utils.datastructures import SortedDict

class Choices(SortedDict):
    def __init__(self, *choices):
        super(Choices, self).__init__()
        for choice in choices:
            self[choice[0]] = choice[1]
    
    @property
    def choices(self):
        choices = []
        for key, value in self.items():
            choices.append( (key, value,) )
        return tuple(choices)
    
    def __iter__(self):
        return self.choices.__iter__()

# Choices implementation

class MyForm(forms.Form):
    CHOICE1 = 0
    CHOICE2 = 1
    CHOICE3 = 2
    CHOICES = Choices(
        (CHOICE1, 'Choice 1'),
        (CHOICE2, 'Choice 2'),
        (CHOICE3, 'Choice 3'),
        )
    field = forms.ChoiceField(
            choices=CHOICES, )
    
    

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.