Hello everyone!
I run into a problem.
I have 3 models:
class Category(models.Model):
name = models.CharField(max_length=120,default='', verbose_name=_('name'))
color = ColorField(default='#FF0000')
class Product(models.Model):
name = models.CharField(max_length=120)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None)
def __str__(self):
return self.category.name + '\t|\t' + name
class Albom(models.Model):
name = models.CharField(max_length=120, verbose_name=_('name'))
products = models.ManyToManyField(to=Product, verbose_name=_('Products'))
I am trying to color the ManyToMany field in the Albom model based on the category’s color.
I kind of did this to the product admin: https://stackoverflow.com/questions/62886686/change-admin-form-field-with-a-custom-one
I want every product to be with the category’s color but it’s not happening:
I created my own class the inherent from FilteredSelectMultiple
and change the color of the option’s text:
class customFilteredSelectMultiple(FilteredSelectMultiple):
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
option_dict = super(customFilteredSelectMultiple, self).create_option(name, value,
label, selected, index, subindex=subindex, attrs=attrs)
label = label.replace('\t', '') # label will be equal to <category_name>\t|\t<product_name>
category, full_name = label.split('|')
option_dict['attrs']['style'] = 'color: ' + Category.objects.get(name=category).color + ';' # changing the color attribute of the option
return option_dict
And I change my form in the Albom Admin:
class AlbomCastumAdmin(admin.ModelAdmin):
form = AlbumAdminForm
formfield_overrides = {
models.ManyToManyField: {'widget': customFilteredSelectMultiple},
}
And this is the form I replaced with:
class AlbumAdminForm(ModelForm):
products = ModelMultipleChoiceField(queryset=Product.objects.all(), widget=customFilteredSelectMultiple(verbose_name='test2',is_stacked=False))
class Meta:
model = Albom
fields = ('name', 'products',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
But it does not seem to change the colors of the options…
What is interesting is that when I change:
class customFilteredSelectMultiple(FilteredSelectMultiple):
with:
class customFilteredSelectMultiple(SelectMultiple):
and in AlbumAdminForm
I change:
products = ModelMultipleChoiceField(queryset=Product.objects.all(), widget=customFilteredSelectMultiple(verbose_name='test2',is_stacked=False))
to:
products = ModelMultipleChoiceField(queryset=Product.objects.all(), widget=customFilteredSelectMultiple()) # not taking params in __init__
It dose show the colors:
But I want to use the FilteredSelectMultiple
and not SelectMultiple
,
What is the problem I don’t see?