Search code examples
pythondjangootree

How to access the human-readable name using get_FOO_display


Hello I have the next code to show to my participants the text of the response that the gave me in a anterior session.

    J11 = models.IntegerField(
        choices=[
            [-2, 'Muy moralmente inapropiado'],
            [-1, 'Moralmente inapropiado'],
            [0, 'No aplica'],
            [1, 'Moralmente apropiado'],
            [2, 'Muy moralmente apropiado'],
        ],
        widget=widgets.RadioSelect
    )
    TJ11 = models.CharField(max_length=2, choices=J11)

When I try to prove this code I get the next error:

File "C:\Users\diese\iat\incentivos\models.py", line 140, in <module>
 class Player(BasePlayer):
File "C:\Users\diese\iat\incentivos\models.py", line 216, in Player
 TJ11 = models.CharField(max_length=2, choices=J11)
File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py",   line 386, in __init__super().__init__(max_length=max_length, **kwargs)
File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 217, in __init__
fix_choices_arg(kwargs)
File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py",   line 195, in fix_choices_arg
choices = expand_choice_tuples(choices)
File "c:\users\diese\appdata\local\programs\python\python37\lib\site- packages\otree\common_internal.py", line 118, in expand_choice_tuples
if not isinstance(choices[0], (list, tuple)):
TypeError: 'IntegerField' object is not subscriptable

What Can I do? Someone has experienced the same ?

Thanks in advance


Solution

  • You can define choices before you define your field and then assign those choices to the field afterwards . This allows you to assign those choices to multiple fields:

    MY_CHOICES = (
        (-2, 'Muy moralmente inapropiado'),
        (-1, 'Moralmente inapropiado'),
        (0, 'No aplica'),
        (1, 'Moralmente apropiado'),
        (2, 'Muy moralmente apropiado'),
    )
    J11 = models.IntegerField(choices=MY_CHOICES)
    TJ12 = models.CharField(max_length=20, choices=MY_CHOICES)