Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django add class to form <input ..> field

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.

like image 262
user590028 Avatar asked Mar 12 '11 20:03

user590028


1 Answers

You could use child selector like this:

.fieldWrapper > input {border: 1px solid #666;line-height:22px;height:22px;padding:3px 5px;width:205px;}
like image 136
tuscias Avatar answered Sep 21 '22 01:09

tuscias