Widget attributes in Admin

I have created a ModelForm for a model called Client.
I added widgets so the the inputs for the ‘SKU’ and ‘VAT Reg No’ fields are in uppercase:

class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ("client_type", "name", "sku", "vat_reg_no", "comments", "avatar", )
        widgets = {
            "sku": TextInput(attrs={"class": "text-uppercase"}),
            "vat_reg_no": TextInput(attrs={"class": "text-uppercase"}),
        }

This works as expected in the form, but when I use this form in Admin then the uppercase conversion does not work:

@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
    form = ClientForm

I have obviously missed a step but can’t see what I’ve done wrong.

The admin does a lot of meta stuff, for that you probably going to need to define the formfield_overrides on your ModelAdmin

Okay, I’ll take a look into that, thanks.

In case anyone else arrives here with the same problem, this is how I fixed it…

I made the schoolboy error of trying to use text-uppercase in the admin pages but, of course, text-uppercase is a Bootstrap class - D’oh!

Before biting the bullet and installing something like Jazzmin (which I will probably do eventually but don’t have the time right now), I dug around a bit more.

The solution is to implement formfield_for_dbfield() in the xxxAdmin class and apply “text-transform: uppercase” to the appropriate field styles:

    def formfield_for_dbfield(self, db_field, request, **kwargs):
        field = super().formfield_for_dbfield(db_field, request, **kwargs)
        if db_field.name == "sku" or db_field.name == "vat_reg_no":
            field.widget.attrs["style"] = "text-transform: uppercase"
        return field

As a side note, you can also identify media assets such as css or js files with a form. See Form Assets (the Media class) | Django documentation | Django. This should result in any necessary css files being loaded any time the form is rendered - including in the admin.