BleuBizarre
BleuBizarre

Reputation: 378

Django add specific attribute for form select options

I have a two models :

class Font(models.Model):
    name = models.CharField(max_length=64)
    css_value = models.CharField(max_length=128)

    def __str__(self):
        return self.name


class DesignOverride(models.Model):
    x_font = models.ForeignKey(Font, null=True, blank=True, on_delete=models.SET_NULL)

In my ModelForm for 'DesignOverride' I am calling 'x_font' using the widget select :

class DesignOverrideForm(forms.ModelForm):

    class Meta:
        model = DesignOverride
        fields = ['x_font']
        widgets = {
            'x_font': forms.Select(attrs={ 'class': 'form-control'})
        }

I wanted to know if there was a way from Django to customize my options by giving them the style 'font-family: X' where X is the css_value of the options Font.

I tried to loop in the 'x_font' select field in the template but seems it's only having the options as string (and therefore lost the information about 'css_value').

Upvotes: 0

Views: 1115

Answers (1)

BleuBizarre
BleuBizarre

Reputation: 378

I created a Select widget override like this:

class FontSelect(forms.Select):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
        option = super(FontSelect, self).create_option(name, value, label, selected, index, subindex=None, attrs=None)

        if option['value']:
            option['attrs']['style'] = "font-family: '" + Font.objects.get(pk=option['value']).css_value + "'"
        print(option)
        return option

Upvotes: 3

Related Questions