Hello all,
I'd like an easy way to customize one or more form fields after being
instantiated by a ModelForm. I didn't find anything close in the docs
so I came up with the following:
from django.forms import ModelForm
class CustomModelForm(ModelForm):
# a mapping of field names to attr./value dicts
field2attrs = {}
def __init__(self, *args, **kwargs):
super(CustomModelForm, self).__init__(*args, **kwargs)
for name,attrs in self.field2attrs.iteritems():
field = self.fields[name]
for attr,val in attrs.iteritems():
setattr(field,attr,val)
#==== usage ===============
class QnAForm(CustomModelForm):
field2attrs = {
'question': dict(widget=TextInput(attrs={'size':100})),
'answer': dict(required=False),
}
class Meta:
model = models.QnA
Is there a better way to do it ? If not, I think it might be useful
enough to be added in the base ModelForm.
George
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---