Django Admin Drop down selections
This can be done via the model field argument choices
myfield = models.CharField(max_length=256, choices=[('green', 'green'), ('red', 'red')])
The only problem with this is that if you already have a value in the database that doesn't match one of these, django might just default it to one of the choices.
If that's a problem and you want to preserve those values, I might override the admin form and either only supply the ChoiceField
on add operations or dynamically add whatever is in the DB as one of the valid choices.
class MyForm(ModelForm):
MY_CHOICES = [('green', 'green'), ('red', 'red')]
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance.id:
CHOICES_INCLUDING_DB_VALUE = [(self.instance.field,)*2] + self.MY_CHOICES
self.fields['my_field'] = forms.ChoiceField(
choices=CHOICES_INCLUDING_DB_VALUE)
class MyAdmin(admin.ModelAdmin):
form = MyForm