How do I add a placeholder on a CharField in Django?

前端 未结 9 1364
执笔经年
执笔经年 2020-11-28 19:53

Take this very simple form for example:

class SearchForm(Form):
    q = forms.CharField(label=\'search\')

This gets rendered in the templat

9条回答
  •  旧巷少年郎
    2020-11-28 20:21

    Most of the time I just wish to have all placeholders equal to the verbose name of the field defined in my models

    I've added a mixin to easily do this to any form that I create,

    class ProductForm(PlaceholderMixin, ModelForm):
        class Meta:
            model = Product
            fields = ('name', 'description', 'location', 'store')
    

    And

    class PlaceholderMixin:
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            field_names = [field_name for field_name, _ in self.fields.items()]
            for field_name in field_names:
                field = self.fields.get(field_name)
                field.widget.attrs.update({'placeholder': field.label})
    

提交回复
热议问题