Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin Drop down selections

I use the django admin for updating various data on the MySQL database. I use the basic django admin for this. When entering in new data, I would like to be able to have it so people can only select from a few options to enter in new text data.

For example: The table holds colors, so instead of letting the admin person (data entry individual in our case) just enter in anything into the text box, how can I get the django admin to only give them several options to choose from?

like image 425
Christopher H Avatar asked Nov 24 '11 04:11

Christopher H


1 Answers

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
like image 72
Yuji 'Tomita' Tomita Avatar answered Sep 28 '22 07:09

Yuji 'Tomita' Tomita