Use placeholders in django forms

Hi there! Using django with bootstrap and want to use placeholders instead labels? Seems you have something to ask Google 🙂

If you got stuck with this particular topic, here is my solution you can use as a starting point for your own.

The idea is simple: turn labels into placeholders. We need to add placeholder attribute to inputs and remove labels from output.

Solution using intermediate class

class PlaceholderForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(PlaceholderForm, self).__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field:
                if type(field.widget) in (forms.TextInput, ):
                    field.widget.attrs.update(
                        {'placeholder': field.label, 'class': 'span10'}
                    )
                if type(field.widget) in (forms.Select, ):
                    field.widget.attrs.update({'class': 'span10'})
                    field.empty_label = field.label

    def as_p(self):
        return self._html_output(
            normal_row='<p%(html_class_attr)s>%(field)s%(help_text)s</p>',
            error_row='%s',
            row_ender='</p>',
            help_text_html=' <span class="helptext">%s</span>',
            errors_on_separate_row=True
        )

class MyForm(PlaceholderForm):
    class Meta:
        model = MyModel


That’s it! __init__() do a copy of label, as_p() was pasted from django source with label removed.

Комментариев нет »15.06.2013 03:41:09 | English, Делаю |