tama
tama

Reputation: 315

Adding a choice to a choice field if it is not there

Hi I currently have this model

class Member(models.Model,get_fields):
    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 20)

ROLE_CHOICES = (
    ('PLAYER', 'Player'),
    ('CONDUCTOR', 'Conductor'), 
    ('COMMITTEEMEMBER', 'Committee Member'),
    ('LIBRARIAN', 'Librarian'),
    ('TUTOR', 'Tutor'),
    ('ACCOUNTANT', 'Accountant'),
    ('PRESIDENT', 'President'),
    ('CHAIRMAN', 'Chairman'),
    ('SECRETARY', 'Secretary'),
    ('OTHER', 'Other')
)
role_choices = models.CharField(_('Role'), max_length = 20, choices = ROLE_CHOICES)

I would like a user to be able to add an extra role choice if it is not available. So I have also created

class ExtraRole(models.Model,get_fields):
    name = models.CharField(max_length = 20)

How would I set up the form so that a user is able to create an extrarole on the create member view if it does not exist and then add it into the role_choices tuple? Is it possible to add foreignkeys to the role_choices tuple? Would that be the correct way to do so?

Upvotes: 1

Views: 133

Answers (1)

hellsgate
hellsgate

Reputation: 6005

It would be possible to add something similar to a foreign key to role_choices, but this would be very convoluted to create and would also be the 'wrong' way to do it. You should create a new model for role choices. Using tuples as your choices is fine if the choices won't change, but if you want to give users the ability to edit these choices then you need to create it as a model and add a foreign key field to the member model

class MemberRole(models.Model):
    name = models.CharField(max_length=20)

class Member(models.Model, get_fields):
    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 20)
    role_choices = models.ForeignKey(MemberRole)

Upvotes: 1

Related Questions