Extending Form to include 'placeholder' text

16 views
Skip to first unread message

Rich Rauenzahn

unread,
Mar 22, 2016, 12:56:33 PM3/22/16
to Django users
Hi,

I'd like to make a mixin to set the placeholder text in the widget attrs.

Reading this https://code.djangoproject.com/ticket/5793, it seems that extending Meta for custom fields is somewhat discouraged.

Would the following be the recommended way to do it?  Just adding a class variable to the Form class?

class PlaceHolderMixin(object):                                                 
                                                                                
    placeholders = {}                                                           
                                                                                
    def __init__(self, *args, **kwargs):                                        
        super(PlaceHolderMixin, self).__init__(*args, **kwargs)                 
        for field_name, field in self.fields.items():                           
            if field_name not in self.placeholders:                             
                continue                                                        
            self.fields[field_name].widget.attrs['placeholder'] = self.placeholders[field_name]


class MyForm(PlaceHolderMixin, ModelForm):                               
                                                                                
    placeholders = {                                                            
        'name': 'blah blah',                    
        'owner': 'blah blah',
    }                                                                           
                                                                                
    class Meta:                                                                 
        model = MyModel
 
Reply all
Reply to author
Forward
0 new messages