How to add additional classes to django form field

mishbah

I've just recently learned about:

Form.error_css_class
Form.required_css_class

Docs: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.error_css_class

So by defining 'error_css_class' and 'required_css_class' in forms

class MyForm(forms.Form):
    error_css_class = 'error'
    required_css_class = 'required'

    name = forms.CharField(...)

I can do:

<div class="field-wrapper {{ form.name.css_classes }}">
...
</div>

This will output:

<div class="field-wrapper required">
...
</div>

However I want to add additional classes to the field, e.g I would like to add 'text name' css class for the "name" field. And reading the docs, I think its possible.

https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.BoundField.css_classes

After reading the above I tried to do

self.fields['name'].css_classes('name text')

That doesn't work. I get

'CharField' object has no attribute 'css_classes'

I also tried

name = forms.CharField(css_classes='name text')

TypeError

__init__() got an unexpected keyword argument 'css_classes'

I know I can add extra attr to field widget

self.fields['name'].widget.attrs['class'] = 'name text'

But I want to add css classes to field wrapper.

I could write a custom templatetag... to check field name/type and return appropriate css classes... but if there is something builtin .. I would love to keep my templates clean :-).

Also hardcoding css classes per field is not an option .. as the form fields are dynamic.

Any help will be appreciated.

mishbah

I figured out how to do it using a custom BoundField

from django.forms import forms

class CustomBoundField(forms.BoundField):

    def css_classes(self, extra_classes=None):
        # logic for determining css_classes has been omitted 
        extra_classes = ['name', 'text']
        return super(CustomBoundField, self).css_classes(extra_classes=extra_classes)

In my forms, I overide getitem

def __getitem__(self, name):
    try:
        field = self.fields[name]
    except KeyError:
        raise KeyError('Key %r not found in Form' % name)
    return CustomBoundField(self, field, name)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to add additional fields to form before submit?

How to add additional column to Django QuerySet

Add class to form field Django ModelForm

Django - Add field to form dynamically

django add placeholder text to form field

django - how to add additional parameters to queryset in forms

How to add multiple form field types of choices for a question in django?

How to add space between underline classes in mat-form-field elements?

Add an additional field to a query

django-allauth Custom signup form. How to add a field with image uploadI(image field)?

How to add an GenericRelation field in a form in Django

How to add an additional field to Vuetify date picker?

How to add additional fields to form after submit

How to add additional context to a django form widget

WooCommerce: Add additional form field attributes to WC Vendors Pro

Django - How to add a validator to form field (instead of setting it)

How to add a form as field attribute in a django ModelForm

How to add a html list to a Django form field

how remove field from admin view during add form django

How to add additional field in Django REST Framwork Serializer GET return

How to add an attribute to the form tag itself and not just a field in Django?

How to add searchable choice field in django form

How to add manytomanyfield attributs with form instead select option field in Django?

How to edit a form field to add some condition using Django template

How to properly add a custom field as a callable to Django admin change form?

Dynamically add field to a form python django

How to validate form field in django?

Add additional field to response in pytest-django

How to pass form field without filling in Django? And add extra field to for answer?