Login

Add HTML Attributes in Model

Author:
guettli
Posted:
May 15, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Maybe there is a better solution, feedback welcome!

 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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

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?

#

guettli (on August 18, 2008):

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 <htmltags>. I use it only for the attribute size and class.

I won't use it for things like "onchange".

#

Please login first before commenting.