dotty dotty - 1 year ago 85
Python Question

make ChoiceField() take any value

I'm using the forms framework and I'm using a but of javascript magic to inject some values on the fly into a select box (the values of this select box relies on a value form another).

Basically you have Team and Players. You need to define a player, but the players data comes from a Team.

In my form class i have

team = forms.ModelChoiceField(queryset=Team.objects.all()
player = forms.ChoiceField()

In the front end when the user selects a team from the select box, the (empty) players boxes gets correctly updated with new data. However when i hit submit, the player select box throws a error
Select a valid choice. 2 is not one of the available choices.
2 IS a valid choice however.

Is there any way around this? Can i make the ChoiceField() take any value?

Answer Source

Ordered by complexity DESC:

  1. Prepopulate it with all possible choices. For example, if you select player's id, it will be choices = Player.objects.values_list('id', flat=True)
  2. Define it as CharField, but render it manually in template as select box.
  3. Don't define it in form, but pass it's value to form's constructor (which you need to override to process this value.)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download