Django add class to form <input ..> field
Asked Answered
R

1

7

We are looking for a solution to add a CSS class attribute to a Django form's <input..> field. We've seen the advice that suggests we wrap the field in a <div> http://docs.djangoproject.com/en/1.2/topics/forms/#customizing-the-form-template, but this advice mainly seems to apply to a fields label, not it's <input ...>.

This particular advice doesn't work if you are trying to create a border around the <input> field. In that case, the <div> will be applied to the bounding box, and not the actual input field. For example .wrapper { border: 1px solid #666;line-height:22px;height:22px;padding:3px 5px;width:205px;} will create a box around the field, rather than replace the default <input ...> border.

We've fallen back to applying the class through a widget applied to the Form class, but this lacks a certain amount of code elegance (and violates DRY). For example, this solves the need.

class ContactUsForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class':'form_text'}))

But of course, this ties the Form very tightly to the CSS. And it get's even more complex if you are trying to apply class attributes to <input ..> fields if the form is based instead on the cool new forms.ModelForm system.

We've spent the better part of two days playing with this issue (and studying Django source code), and it looks like we may be reaching the farthest edges of Django for this one particular issue -- but we just wanted to take one pass at StackOverflow to see if anyone else had insight.

Thanks for any insight.

One final comment: feel free to set us straight on this if the problem is our understanding CSS (rather than django). We've spent quite a bit of time messing with CSS options, but none of them seem to allow us to accomplish the effect desired -- that is replacing the default <input...> border.

Rotund answered 12/3, 2011 at 20:48 Comment(1)
For formatting the <input> with CSS this is fine, but if you want to do it to add, for example, form-control for Bootstrap/MDBootstrap, refer to Add class to form field Django ModelForm - Stack OverflowPapist
E
8

You could use child selector like this:

.fieldWrapper > input {border: 1px solid #666;line-height:22px;height:22px;padding:3px 5px;width:205px;}
Emplane answered 12/3, 2011 at 21:6 Comment(1)
Brilliant solution! I don't usually think about child-selectors because of the historical compatibility issues, but if you don't mind targeting modern browsers -- this is a non-issue. Thanks for the great solution.Rotund

© 2022 - 2024 — McMap. All rights reserved.