user1159517
user1159517

Reputation: 6350

Django ModelChoiceField to_field_name is not working

I have following models and i'm trying to use Django ModelForm's ModelChoiceField to solve my problem quickly

Class Games(Model):
   code = charField()  # GTA, ABC, etc..
   name = charField()  # Grand Tourismo, ALL BBB CCC , etc..
   unique_together(code, name)

class Settings(Model):
   gameCode = charField(). #Didn't use Foreign key because of internal reasons where we can't use Games model somewhere outside
   username = charField()
   ...

class GameCodeChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
         return obj.name

class SettingsForm(forms.ModelForm):
   gameCode = GameCodeChoiceField(queryset=None,required=False)
    class Meta:
        model = Settings
        fields = ['username']

    def __init__(self, *args, **kwargs):
        super(SettingsForm, self).__init__(*args, **kwargs)

        self.fields['gameCode'].queryset = Games.objects.filter(game=game, isActive=True)
        self.fields['gameCode'].to_field_name = 'code'

Now, When i try to save SettingsForm, I'm getting GameCode = 'GameCode Object' instead of the code like GTA..

Please help. Edited.

Upvotes: 0

Views: 2119

Answers (1)

Chandler Barnes
Chandler Barnes

Reputation: 81

to_field_name changes the values of the generated option elements, not the display text.

You want to add a __str__ method to your model. It will change the display of each object instance listed in the select element.

Class Games(Model):
   code = charField()  # GTA, ABC, etc..
   name = charField()  # Grand Tourismo, ALL BBB CCC , etc..
   unique_together(code, name)

   def __str__(self):
      return self.code

Upvotes: 1

Related Questions