Django Dropdown

I am using admin django to update various data in a MySQL database. For this, I use the main django admin. When entering new data, I would like to be able to have this so that people can only choose from a few options for entering new text data.

For example: The table contains colors, so instead of letting the administrator (entering data individually in our case) just enter something into the text box, how can I force the django administrator to provide only a few options?

+8
django django-admin
source share
1 answer

This can be done using the choices model field argument choices

 myfield = models.CharField(max_length=256, choices=[('green', 'green'), ('red', 'red')] 

The only problem is that if you already have a value in the database that does not match one of them, django might just use one of the options by default.

If this is a problem and you want to save these values, I can redefine the administrator form and either supply only ChoiceField in the add operations, or dynamically add everything in the database as one of the valid options.

 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 
+18
source share

All Articles