Search code examples
djangodjango-views

Django views.py Lookup value from constant list


In a django views.py how do you take a selection (number) from input can get the matching "Description"? For example the user selects 3 and returns "Yellow"

colors = [
    ('0','black'),
    ('1','white'),
    ('2','Red'),
    ('3','Yellow'),
    ('4','Blue'),
    ('5','Green')
    ]

...

colorSelection = form.cleaned_data.get('color')

#lookup color description
colorDescription = ???

Solution

  • You will need to make a dictionary, or at least something to look up the description, so:

    COLORS = [
        ('0', 'black'),
        ('1', 'white'),
        ('2', 'Red'),
        ('3', 'Yellow'),
        ('4', 'Blue'),
        ('5', 'Green'),
    ]
    
    # …
    
    colorSelection = form.cleaned_data.get('color')
    colorDescription = dict(COLORS).get(colSelection)

    Since however, one often specifies these choices with a TextChoices instead, and this then makes a lookup more convenient:

    class ColorChoices(models.TextChoices):
        BLACK = '0', 'black'
        WHITE = '1', 'white'
        RED = '2', 'red'
        YELLOW = '3', 'yellow'
        BLUE = '4', 'blue'
        GREEN = '5', 'green'

    Then we can look it up with:

    ColorChoices(colSelection).label