Add HTML Attributes in Model

 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

Comments

humphreymurray (on May 19, 2008):

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?

#

jedie (on July 25, 2008):

My solution: http://www.djangosnippets.org/snippets/916/

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.