Assuming that I have such model
COLORS= (
('R', 'Red'),
('B', 'Yellow'),
('G', 'White'),
)
class Car(models.Model):
name = models.CharField(max_length=20)
color= models.CharField(max_length=1, choices=COLORS)
It displays as a selectbox in the admin panel however I would like my admin-user to multi select those colors like many-to-many relationship, how can this be achieved without a ('RB', 'Red&Blue'), type of logic
Can a
Carhave multiplecolors? In that casecolorought to be a many to many relationship rather than aCharField. If on the other hand you want to do something like Unix permissions (i.e. Red + Blue, Red + Blue + Green etc.) then assign numeric values of to each of them and makecoloran integer field.Update
(After reading comment) You can use a custom form to edit your model in Admin instead of the default
ModelForm. This custom form can use a multiple choice widget that lets users select multiple colors. You can then override theclean()method of the form to return a suitably concatenated value (‘RB’ etc.).Update 2
Here is some code:
First, remove the choices from the model field. Also increase its maximum size to 2. We don’t want choices here – if we do, then we’ll have to add a choice for each combination of colors.
Second add a custom
ModelFormto use in admin app. This form will override color and instead declare it as a multiple choice field. We do need choices here.Note that I have added only a couple of validations. You may want more and/or customize the validations.
Finally, register this form with admin. Inside your
admin.py: