#1 by janohirmas
Hi everyone,
I am programming an experiment where the player class has a sequence of variables with common names that depend on a game constant. I want to run something like:
for i in range(1,C.iOpts+1):
exec(f"dec{i} = models.StringField()")
If I run the server and add this, it works perfectly, but if I open the server, I get an error saying that player has variable 'i' that is nor a model field:
Error(title='NonModelFieldAttr: Player has attribute "i", which is not a model field, and will therefore not be saved to the database. Consider
changing to "i = models.IntegerField(initial=13)"', id=111, app_name='Task1')
Is there any way around this?
Thanks!
#2
by
BonnEconLab
After class Player(BasePlayer):, put the following on the top level of your __init__.py file — that is, OUTSIDE class Player(BasePlayer):
for i in range(1, C.iOpts + 1):
setattr(Player, f"dec{i}", models.IntegerField())
See the post by gr0ssmann on https://www.otreehub.com/forum/202/.
For the associated page, you can use a loop as follows if you would like to include all of the generated player fields:
class MyPage(Page):
form_model = 'player'
form_fields = [f'dec{i}' for i in range(1, C.iOpts + 1)]
#3 by janohirmas
Thank you!