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, ):
                        {'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(
            help_text_html=' <span class="helptext">%s</span>',

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, Делаю |

Оставить комментарий