1

I have ModelForm where i use Django Forms.ChoiceField. Writing the value to the database works. But when i open the url, the dropdown list is not showing the previously selected value as selected value.

I tried setting initial=value, but it's not working as well.

class GameForm(forms.ModelForm):
   gameCode = forms.ChoiceField(required=False)

   def __init__(self, *args, **kwargs):
        obj = AllGameCodes.objects.filter(game=game)
        choices = []
        choices.append(('', '-----------'))
        for i in obj:
            choices.append((i.code,i.description))
        self.fields['gameCode'].choices = choices


in views.py,

game = games.objects.get(id=1)
form = GameForm(request.POST, initial={'code':game.code}
user1159517
  • 5,390
  • 8
  • 30
  • 47
  • You are doing it wrong, you must use `self.fields[""]` for reaching bound form data. But also, there is a similar question [in here](http://stackoverflow.com/questions/871037/django-overloading-init-for-custom-forms) – Mp0int May 12 '15 at 06:41
  • what is bound form data here? – user1159517 May 12 '15 at 06:47
  • Are you not calling super's init() ? – Rohan May 12 '15 at 06:52
  • `Bound` is the wring word in here I guess, It was not so clear according to what I want to say, so bound is quite wrong here. [Bound & unbound form data](https://docs.djangoproject.com/en/1.8/ref/forms/api/). I just realize your porblem is quite different – Mp0int May 12 '15 at 06:54
  • super(GameForm, self).__init__(*args, **kwargs) – user1159517 May 12 '15 at 06:54
  • Yes. I'm calling super in __init__ – user1159517 May 12 '15 at 06:55
  • You must take `game` variable from kwargs, `es.objects.filter(game=game)` is wrong. Use `game=kwargs["game"]` – Mp0int May 12 '15 at 07:00

2 Answers2

1

You must take game variable from kwargs. Also using ModelChoicefield may ease your solution

def __init__(self, *args, **kwargs):
    super(GameForm, self).__init__(*args, **kwargs)
    _game = kwargs.get("game"):
    if _game:
        self.fields['gameCode'] = ModelChoiceField(queryset=AllGameCodes.objects.filter(game=_game), required=False)
Mp0int
  • 18,172
  • 15
  • 83
  • 114
0

For future reference, you may use form = GameForm(instance=game) to load the form with the model data and write new data to that model. Also instead of overwriting the form class, you can alter fields in your view

#views.py

game = games.objects.get(id=1)
form = GameForm(request.POST, instance=game)
form.fields['gameCode'].queryset = AllGameCodes.objects.filter(game=game)