[Fixed]-Django Admin Drop down selections

33👍

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

2👍

It’s better to define a "models.CharField" field type in your model

your_choices = (
        ('1', u'yello'),
        ('2', u'red'),
        ('3', u'black'),
    )

types = models.CharField(max_length=32, choices=your_choices, null=True, blank=True)

Then in "admin.py" you should add this new field in your custom admin class like below.

class YourModelAdmin(admin.ModelAdmin):
    fields = ('types', )

admin.site.register(YourModel, YourModelAdmin)

Leave a comment