Easy way to add attribute to *all* InputText elements in Django?
I want to add class="text"
to all the TextInput
widgets. I know I can add
widgets = {
'myfield': TextInput(attrs={'class':'text'})
}
For every single field开发者_JAVA技巧, in every single form... but there's got to be an easier way? A lot of my forms are based on ModelForms, so it sets the field and widget automatically for me.
Maybe you could do that by subclassing ModelForm with a class that overrides the __init__
method with one that calls super __init__
and then goes over the created object's attributes, and if they are instances of TextInput
, adds the attribute. You can probably figure out the specific mechanisms for the solution.
That's what I would explore.
Not that this is the best or cleanest solution, but what about using jQuery?
$(document).ready(function(){
$('input[type=text],input[type=password]').addClass('text');
});
I am assuming that the goal of this is styling text input, as IE6 won't understand CSS attributes
This is a Django based solution, the already mentioned. You could create an app "MyForms" and have a forms module there:
# myforms/forms.py
from django import forms
class Form(forms.Form):
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
for field in self.fields:
# Turn all CharField widgets to TextInput(attrs={'class'='text'})
class ModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# Same as above
Then in your code, just do this:
from myforms import forms
instead of
from django import forms
精彩评论