1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class formfield_widget_attrs(object):
u'''
Add HTML attributes to Form Fields created by ModelForm:
Example: <input> tag should have attribute size=60:
class MyModel(models.Model):
name=models.CharField()
name.formfield=modelutils.formfield_widget_attrs(name.formfield, size='60')
'''
def __init__(self, method, **kwargs):
self.method=method
self.kwargs=kwargs
def __call__(self, *args, **kwargs):
formfield_instance=self.method(*args, **kwargs)
formfield_instance.widget.attrs.update(self.kwargs)
return formfield_instance
|
More like this
- check if form has changed (deprecated) by guettli 5 years, 2 months ago
- Add model form field meta data in a DRY way by jedie 4 years, 2 months ago
- Timedelta Database Field by guettli 4 years, 8 months ago
- form_for_model / instance customized save and model aware validation by fivethreeo 6 years ago
- change a widget attribute in ModelForm without define the field by jedie 4 years, 9 months ago
Comments
I wouldn't include html formating in the model. It defeats the purpose of having separator between the model and the form. The form would be a better place for this logic?
#
My solution: http://www.djangosnippets.org/snippets/916/
#
Reply to humphreymurray: I think it is OK to have this in the model. You can set the default size there. Of course custom models can override this.
And: I don't but HTML in the model. I just pass a dictionary which map do attributes. There are no [HTML_REMOVED]. I use it only for the attribute size and class.
I won't use it for things like "onchange".
#