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

前端 未结 9 1377
执笔经年
执笔经年 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:13

    The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@address.nl'
    

    It also allows the placeholder to depend on the instance for ModelForms with instance specified.

提交回复
热议问题