Django add class to form <input ..> field

99封情书 提交于 2019-12-06 01:51:52

问题


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.


回答1:


You could use child selector like this:

.fieldWrapper > input {border: 1px solid #666;line-height:22px;height:22px;padding:3px 5px;width:205px;}


来源:https://stackoverflow.com/questions/5285396/django-add-class-to-form-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!