Reputation: 435
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 designation
s, 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
Reputation: 476699
I think this is mainly an issue with rendering the objects. You can define a __str__
method to specify how the Role
s 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 Role
s with the same designation
.
Upvotes: 2
Reputation: 1466
add
def __str__(self):
return self.designation
to your Role
class and all your choices become real names)
Upvotes: 2