mashedpotatoes
mashedpotatoes

Reputation: 435

How to display a ForeignKey field in a ModelForm with no default value?

I need to create a form for Player that has Role objects as choices in a dropdown field, but with their string field shown instead.

models.py

class Player(models.Model):
    role = models.ForeignKey(role)
    ...

class Role(models.Model):
    designation = models.CharField()

forms.py

class PlayerForm(ModelForm):
    class Meta:
        model = Player
        fields = ['role']

Say I have three role objects with these as their designations, respectively: Warrior, Mage, Rouge, how can I display it in a PlayerForm instance as a dropdown, with no default value so the user has to choose one?

Currently this code displays the objects as the objects themselves (Role object (1), Role object (2), ...)

Upvotes: 2

Views: 50

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

I think this is mainly an issue with rendering the objects. You can define a __str__ method to specify how the Roles should be rendered:

class Role(models.Model):
    designation = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.designation

You also might want to set the designation to a unique=True field, to prevent defining two Roles with the same designation.

Upvotes: 2

Andrey Maslov
Andrey Maslov

Reputation: 1466

add

def __str__(self):
    return self.designation 

to your Role class and all your choices become real names)

Upvotes: 2

Related Questions