css - How to add additional classes to django form field -


i've 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 defining 'error_css_class' , '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 output:

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

however want add additional classes field, e.g add 'text name' css class "name" field. , reading docs, think possible.

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

after reading above tried do

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

that doesn't work. get

'charfield' object has no attribute 'css_classes' 

i tried

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

typeerror

__init__() got unexpected keyword argument 'css_classes' 

i know can add attr field widget

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

but want add css classes field wrapper.

i write custom templatetag... check field name/type , return appropriate css classes... if there builtin .. love keep templates clean :-).

also hardcoding css classes per field not option .. form fields dynamic.

any appreciated.

i figured out how using custom boundfield

from django.forms import forms  class customboundfield(forms.boundfield):      def css_classes(self, extra_classes=none):         # logic determining css_classes has been omitted          extra_classes = ['name', 'text']         return super(customboundfield, self).css_classes(extra_classes=extra_classes) 

in forms, 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) 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -